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

Tru*_*ePS 8 java multithreading jvm

这是我的两个班级:

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...");
    }
}
Run Code Online (Sandbox Code Playgroud)

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);   
        }   
    }    
}
Run Code Online (Sandbox Code Playgroud)

现在,当我运行时Firstclass,输出是:

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
Run Code Online (Sandbox Code Playgroud)

我的问题是: 让我们考虑主要方法是由JVM中的线程'T'执行,而t1和t2显然是父线程T的子线程,所以当作为主要方法的T线程死亡时,T1和T2如何仍然执行并给我们输出.因为如果父线程死亡或终止,那么子线程也应该死亡或终止.

Abi*_*san 13

线程之间没有父子关系的概念.一旦两个线程运行,它们基本上是同行.主线程可以在其他线程仍在运行时退出.

Java没有"子"线程的真正概念.当你启动一个线程时,它从"父"继承守护进程和优先级,但这是父/子关系的结束.

  • 从您的收藏夹中删除该链接.如果您有硬拷贝,请将其刻录.包含的'信息'对你有害无益:( (2认同)