在Java线程中启动线程

时间:2019-06-26 05:42:44

标签: java multithreading

说我有线程池,并且我正在该线程池中执行一个名为thread-a的线程的任务 现在,在thread-a中,我正在启动一个新线程,将其称为thread-child(可能是池线程,可能不是),这意味着thread-a将在{{ 1}}开始跑步了吗?或thread-child要死了?

2 个答案:

答案 0 :(得分:5)

不。 Java没有线程的继承。所有线程都是独立的且自持的。即您的 thread-a 将返回到执行池。并且 thread-child 将一直执行到最后(无论 thread-a 发生了什么),并且不会放入执行池中,因为它不是由创建的它。

答案 1 :(得分:1)

这是实际答案:https://stackoverflow.com/a/56766009/2987755
只是添加代码。

ExecutorService executorService = Executors.newCachedThreadPool();
Callable parentThread = () -> {
    System.out.println("In parentThread : " + Thread.currentThread().getName());
    Callable childThread = () -> {
        System.out.println("In childThread : " + 
        Thread.currentThread().getName());
        Thread.sleep(5000); // just to make sure, child thread outlive parent thread
        System.out.println("End of task for child thread");
        return 2; //ignore, no use here
    };
    executorService.submit(childThread);
    System.out.println("End of task for parent thread");
    return 1; //ignore, no use here
};
executorService.submit(parentThread);
Thread.sleep(8000); // wait until child thread completes its execution.
executorService.shutdown();

输出:

In parentThread : pool-1-thread-1
End of task for parent thread
In childThread : pool-1-thread-2
End of task for child thread
相关问题