[英]Starting thread within a thread in Java
Say I have thread pool and I'm executing a task from that thread pool with thread with name thread-a
Now within thread-a
I'm starting a new thread lets call it thread-child
(might be pooled thread and might not) does this means that thread-a
is going back to the thread pool when thread-child
get running? 假设我有线程池,并且正在使用名称为
thread-a
线程从该线程池执行任务,现在在thread-a
我启动了一个新线程,将其称为thread-child
(可能是池线程,可能不是)这是否意味着thread-child
开始运行时, thread-a
将返回线程池? or thread-a
is going to die? 或
thread-a
即将消亡?
No. Java does not have an inheritance for threads. 否。Java没有线程的继承。 All threads are separate and self-sustained.
所有线程都是独立的且自持的。 Ie your thread-a will be put back to execution pool.
即您的线程将被放回执行池。 And thread-child will be executed until the end (no matter what has happened with thread-a ) and will NOT be put into execution pool, because it was not created by it.
并且子线程将一直执行到最后(无论线程a发生了什么),并且不会放入执行池中,因为它不是由它创建的。
This is the actual answer : https://stackoverflow.com/a/56766009/2987755 , 这是实际的答案: https : //stackoverflow.com/a/56766009/2987755 ,
Just adding code in addition to that. 除了添加代码。
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();
Output: 输出:
In parentThread : pool-1-thread-1
End of task for parent thread
In childThread : pool-1-thread-2
End of task for child thread
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.