简体   繁体   English

相当于Python线程守护程序模式的Java线程

[英]Java thread equivalent of Python thread daemon mode

In python I can set a thread to be a daemon, meaning if parent dies, the child thread automatically dies along with it. 在python中,我可以将一个线程设置为守护程序,这意味着如果父线程死亡,则子线程会自动与其一起死亡。

Is there an equivalent in Java? Java是否有等效功能?

Currently I am starting a thread like this in Java, but the underlying child thread does not die and hang even if main thread exits 当前,我正在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;
                 }   

             }       
         });

When you're interacting with bare Thread you can use: 与裸Thread交互时,可以使用:

Thread thread = new Thread(new MyJob());
thread.setDaemon(true);

thread.start();

In your example, there's ExecutorService that needs to be provided with ThreadFactory which should do the similar job - like this: 在您的示例中,需要为ThreadFactory提供ExecutorService ,它应该执行类似的工作-如下所示:

Executors.newSingleThreadExecutor(new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setDaemon(true);

        return thread;
    }
});

I would also recommend using Guava s ThreadFactoryBuilder : 我也建议使用GuavaThreadFactoryBuilder

Executors.newSingleThreadExecutor(
        new ThreadFactoryBuilder()
                .setDaemon(true)
                .build()
); 

It eases setting the most common thread properties and allows for chaining multiple thread factories 它简化了最常见线程属性的设置,并允许链接多个线程工厂

update 更新

As Slaw and Boris the Spider rightfully noticed - you have mentioned the behavior that would cause killing child-thread when parent-thread dies. 正如蜘蛛Slaw和Boris正确注意到的那样-您已经提到了当父线程死亡时会导致杀死子线程的行为。 There's nothing like that either in Python or Java. 在Python或Java中没有类似的东西。 Daemon threads will be killed when all other non-daemon threads exited. 当所有其他非守护程序线程退出时,守护程序线程将被杀死。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM