简体   繁体   中英

Demon threads continue to run after main exited and there is some non-daemon thread still running?

I know that all Demon threads are terminated after main exits. But what if there is some non-daemon thread which continues to run after main exited? Does running of this non-daemon thread prevent all other daemon threads from terminating?

Demon threads continue to run after main exited and there is some non-daemon thread still running?

The runtime shuts down when all non-daemon threads have stopped. So, if you start another non-daemon thread, such as the event queue, the application keeps running.

Daemon threads don't shut down until the JVM terminates.

The JVM won't terminate as long as no thread calls System.exit and there are any non-daemon threads still running.

So yes, a non-daemon thread running prevents the JVM from shutting down, and as long as the JVM is alive it won't force daemon threads to terminate.

From the Java Language Specification, 12.8 Program Exit :

A program terminates all its activity and exits when one of two things happens:

  • All the threads that are not daemon threads terminate.

  • Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.

So be careful to make sure your threads get shutdown properly. On one project I had a background thread that periodically wrote to a file, and I was trying to figure out why the contents of the file were changing wildly. The reason turned out to be that the background thread wasn't getting shutdown so it stuck around and kept doing its thing, even as the newly started application was also writing to the file. Doing ps -af | grep java ps -af | grep java showed that there were 2 java processes running where there should have been one.

Why not checking it yourself ??

public static void main(String[] ...){
Thread t1=new Thread(()=>{for(;;);});
t1.setDeamon(true);

Thread t2=new Thread(()=>{for(;;){System.out.println(new Date())}});
t2.setDeamon(false);

t1.start();
t2.start();
Thread.currentThread().sleep(1000);
}

And check if JVM was terminated or not. If your CPU is 100% busy, then not.

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