Java中的子线程是否阻止父线程终止?
当我在另一个线程中创建并启动一个线程时,它会是一个子线程吗? 在子线程运行时是否阻止父线程终止? 例如:
new Thread(new Runnable() { @Override public void run() { //Do Sth new Thread(new Runnable() { @Override public void run() { //Do Sth new Thread(new Runnable() { @Override public void run() { //Do Sth } }).start(); //Do Sth } }).start(); //Do Sth } //Do Sth }).start();
在您的代码中, 对象之间存在父子关系。 但是, 线程之间没有父子关系的概念。 一旦两个线程运行,它们基本上是同行。
假设线程A启动线程B.除非它们之间有明确的同步,否则任何线程都可以随时终止,而不会影响其他线程。
请注意,只要线程存在,任一线程都可以使进程保持活动状态。 请参阅Java中的守护程序线程是什么?
当我在另一个线程中创建并启动一个线程时,它会是一个子线程吗?
Java没有“子”线程的真正概念。 当你启动一个线程时,它从“父”inheritance守护进程和优先级,但这是父/子关系的结束。
// in Thread.init() this.daemon = parent.isDaemon(); this.priority = parent.getPriority();
线程启动时,它沿着它的“父”运行,两者之间没有联系。
在子线程运行时是否阻止父线程终止?
不,不是的。 但是我怀疑你真的想知道一个线程是否可以阻止应用程序的终止。 如果子线程是非守护进程,那么即使主线程(也是非守护进程)完成,您的应用程序将等待子线程完成。 根据定义,JVM将等待所有非守护程序线程完成。 一旦最后一个非守护程序线程完成,JVM就可以终止。
请参阅: Java中的守护程序线程是什么?
它将成为子线程,但它不会阻止父线程终止。
两个线程中没有父子关系。 完成ParentThread
, ParentThread
不等待ChildThread
。
public class MainThread { public static void main(String[] args) { ParentThread pt=new ParentThread(); pt.start(); for(int i=1;i<=20;i++){ System.out.println("ParentThread alive: "+pt.isAlive()); try{ Thread.currentThread().sleep(500); }catch(Exception ex){ ex.printStackTrace(); } } } } class ParentThread extends Thread{ public void run(){ ChildThread ct=new ChildThread(); ct.start(); for(int i=1;i<=10;i++){ try{ System.out.println("ChildThread alive: "+ ct.isAlive() + ", i = "+i); sleep(500); }catch(Exception ex){ ex.printStackTrace(); } } } } class ChildThread extends Thread{ public void run(){ for(int i=1;i<=20;i++){ try{ System.out.println("ChildThread i = "+i); sleep(500); }catch(Exception ex){ ex.printStackTrace(); } } } }
输出(如):
ParentThread alive: true ChildThread alive: true, i = 1 ChildThread i = 1 ParentThread alive: true ChildThread i = 2 ChildThread alive: true, i = 2 ParentThread alive: true ChildThread i = 3 ChildThread alive: true, i = 3 ParentThread alive: true ChildThread i = 4 ChildThread alive: true, i = 4 ParentThread alive: true ChildThread i = 5 ChildThread alive: true, i = 5 ParentThread alive: true ChildThread i = 6 ChildThread alive: true, i = 6 ParentThread alive: true ChildThread alive: true, i = 7 ChildThread i = 7 ParentThread alive: true ChildThread i = 8 ChildThread alive: true, i = 8 ParentThread alive: true ChildThread alive: true, i = 9 ChildThread i = 9 ParentThread alive: true ChildThread alive: true, i = 10 ChildThread i = 10 ParentThread alive: true ChildThread i = 11 ParentThread alive: false ChildThread i = 12 ChildThread i = 13 ParentThread alive: false ParentThread alive: false ChildThread i = 14 ParentThread alive: false ChildThread i = 15 ParentThread alive: false ChildThread i = 16 ParentThread alive: false ChildThread i = 17 ChildThread i = 18 ParentThread alive: false ParentThread alive: false ChildThread i = 19 ParentThread alive: false ChildThread i = 20