即使在其父线程死亡或终止之后,子线程如何仍然执行?

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 没有子"线程的真正概念.当您启动一个线程时,它会从父"继承守护进程和优先级,但这就是父/子关系的结束.

这篇关于即使在其父线程死亡或终止之后,子线程如何仍然执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:即使在其父线程死亡或终止之后,子线程如何仍然执行?

基础教程推荐