在python中,我可以将线程设置为守护进程,这意味着如果父线程死亡,子线程会自动随之死亡。
Java中有等价物吗?
目前我正在 Java 中启动这样的线程,但即使主线程退出,底层子线程也不会死亡和挂起
executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
while (true) {
//Stopwatch stopwatch = Stopwatch.createStarted();
String threadName = Thread.currentThread().getName();
System.out.println("Hello " + threadName);
try {
Thread.sleep(1*1000);
} catch (InterruptedException e) {
break;
}
}
});
当您与裸Thread
交互时,您可以使用:
Thread thread = new Thread(new MyJob());
thread.setDaemon(true);
thread.start();
在您的示例中,需要提供ExecutorService
应该执行类似工作的ThreadFactory
- 如下所示:
Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
我还建议使用Guava
ThreadFactoryBuilder
:
Executors.newSingleThreadExecutor(
new ThreadFactoryBuilder()
.setDaemon(true)
.build()
);
它简化了最常见的线程属性的设置,并允许链接多个线程工厂
更新
正如蜘蛛斯劳和鲍里斯正确地注意到的那样 - 你提到了当父线程死亡时会导致杀死子线程的行为。在Python或Java中都没有这样的东西。当所有其他非守护程序线程退出时,守护程序线程将被终止。