简体   繁体   中英

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.

Is there an equivalent in 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

         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 = 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:

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 :

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. There's nothing like that either in Python or Java. Daemon threads will be killed when all other non-daemon threads exited.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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