[英]Using daemon threads in a Java threadpool is not working
我有一个通过Executors.newFixedThreadPool()
创建的Java线程池,我想使用守护程序线程。
原因是这是一个GUI应用程序,我不希望这些线程导致程序在Window关闭后保持运行。
我实现了一个自定义ThreadFactory
,它在它创建的线程上设置Thread.setDaemon(true)
。
这个课是这样的:
import java.util.concurrent.ThreadFactory;
public class DaemonThreadFactory implements ThreadFactory{
public Thread newThread(Runnable runnable){
Thread thread = new Thread();
thread.setDaemon(true);
return thread;
}
}
出于某种原因,当我将DaemonThreadFactory
与Executors.newFixedThreadPool()
一起使用时,我的任何排队任务都不会被执行。 如果我将它改回常规的ThreadFactory
它就可以了。
我究竟做错了什么?
你没有将Runnable
传递给线程,所以没有代码可以执行:
@Override
public Thread newThread(Runnable runnable)
{
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
}
您忽略了传递给您的Runnable,Thread必须将其包装。
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
否则你创造的线程实际上什么都不做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.