当线程在Java中死亡时,ThreadPoolExecutor会发生什么 [英] What happens to the ThreadPoolExecutor when thread dies in Java

查看:111
本文介绍了当线程在Java中死亡时,ThreadPoolExecutor会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个线程,该线程又创建了一个ThreadPoolExecutor并向其提交一些长时间运行的任务.在某些时候,原始线程由于未处理的异常/错误而死亡.执行程序应该怎么办(它是该死线程的本地对象,没有外部引用该死线程)?是否应该GC?

I have created a thread which in turn creates a ThreadPoolExecutor and submits some long running tasks to it. At some point, the original thread dies due to unhandled exception/error. What should happen to the executor (it's local to that dead thread, no external references to it)? Should it be GCed or not?

这个问题从一开始就被错误地提出,但是我会把它保留下来,因为格雷提供了有关TPE工作原理的一些很好的细节.

this question was formulated incorrectly from the beginning, but I will leave it as Gray provided some good details of how TPE work.

推荐答案

线程被称为 GC根.这意味着,除其他外,无法收集正在运行的(或未启动的)线程.这也意味着无法从这些线程引用的对象被收集,这就是为什么您可以执行new Thread(new MyRunnable()).start()之类的事情,或者在没有任何引用的情况下使线程池运行的原因.

Threads are so called GC roots. This means among other things, that a running (or an unstarted) thread can't be collected. It also means that objects that are being referenced from those threads can't be collected, which is why you can do things like new Thread(new MyRunnable()).start(), or have threadpools running without you having any reference to them.

如果线程是守护程序,则所有其他非守护程序线程都已停止时,它可以自动停止.您可以使用带有守护程序线程的线程池,但是最好的办法是确保正确清理所有内容(即,异常不应杀死本应最终停止并清理线程池的线程).

If the thread is a daemon, it can stop automatically if all other non-daemon threads have stopped. You can have threadpools with daemon threads, but the best thing is to make sure that things are cleaned up properly (i.e. an exception shouldn't kill the thread that's supposed to eventually stop and cleanup the threadpool).

这篇关于当线程在Java中死亡时,ThreadPoolExecutor会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆