How can child threads still execute even after that their parent thread die or terminate?(即使在其父线程死亡或终止之后,子线程如何仍然执行?)
问题描述
这是我的两个课程:
public class Firstclass {
public static void main(String args[]) throws InterruptedException {
System.out.println("Main start....");
Secondclass t1 = new Secondclass();
t1.setName("First Thread");
Secondclass t2 = new Secondclass();
t2.setName("Second Thread");
t1.start();
t2.start();
System.out.println("Main close...");
}
}
和
public class Secondclass extends Thread {
@Override
public void run() {
try {
loop();
} catch(Exception e) {
System.out.println("exception is" + e);
}
}
public void loop() throws InterruptedException {
for(int i = 0; i <= 10; i++) {
Thread t = Thread.currentThread();
String threadname = t.getName();
if(threadname.equals("First Thread")) {
Thread.sleep(1000);
} else {
Thread.sleep(1500);
}
System.out.println("i==" + i);
}
}
}
现在当我运行 Firstclass
然后输出是:
Now when I run Firstclass
then the output is:
Main start....
Main close...
i==0
i==0
i==1
i==1
i==2
i==3
i==2
i==4
i==3
i==5
i==6
i==4
i==7
i==5
i==8
i==9
i==6
i==10
i==7
i==8
i==9
i==10
我的问题是:让我们考虑 main 方法由 JVM 中的线程T"执行,t1 和 t2 显然是父线程 T 的子线程,所以当作为 main 方法的 T 线程死亡时T1 和 T2 怎么还能执行并给我们输出.因为如果父线程死亡或终止,那么子线程也应该死亡或终止.
My question is: Let's consider main method is executed by a thread 'T' in JVM and t1 and t2 are obviously child threads of parent thread T so when T thread that is the main method dies how can T1 and T2 still execute and give us output. Because if parent thread dies or terminates then child thread should also die or terminate.
推荐答案
线程之间没有父子关系的概念.一旦两个线程运行,它们基本上就是对等的.主线程可以退出,而其他线程仍在运行.
There is no notion of a parent-child relationship between threads. Once the two threads are running they're basically peers. The main thread can exit while other thread still running.
Java 没有子"线程的真正概念.当您启动一个线程时,它会从父"继承守护进程和优先级,但这就是父/子关系的结束.
这篇关于即使在其父线程死亡或终止之后,子线程如何仍然执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:即使在其父线程死亡或终止之后,子线程如何仍然执行?


基础教程推荐
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01