Java Daemon Threads Overview

Source: Internet
Author: User

Java threads are divided into two types: User thread, Daemonthread (daemon thread).

The daemon thread works as long as any of the remaining non-daemon threads in the current JVM instance are not finished, and only when the last non-daemon thread is finished, the daemon ends up working with the JVM, and the daemon function is to provide convenience to other threads, the most typical application of which is the GC (garbage collector) , he is a very competent guardian.

The only difference between user and daemon is that the virtual machine leaves: If the user thread is all out of operation, only the daemon thread is present, and the virtual machine exits. Because there is no guardian, Daemon has no work to do, there is no need to continue to run the program.

First look at an example, the main thread to establish a daemon thread, when the main thread ends, the daemon thread also ends.

Package Com.daemon;import Java.util.concurrent.timeunit;public class Daemonthreadtest{public static void Main (String[ ] args) {thread mainthread = new Thread (new Runnable () {@Overridepublic void run () {thread childthread = new Thread (new Clild Thread ()); Childthread.setdaemon (true); Childthread.start (); System.out.println ("I ' m main thread ...");}); Mainthread.start ();}} Class Clildthread implements runnable{@Overridepublic void Run () {while (true) {System.out.println ("I ' m Child Thread:"); Try{timeunit.milliseconds.sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Operation Result:

I ' m child Thread: I ' m main thread ...
If not more than Childthread as the daemon thread, when the main thread ends, Childthread continues to run, as follows:
Package Com.daemon;import Java.util.concurrent.timeunit;public class Daemonthreadtest{public static void Main (String[ ] args) {thread mainthread = new Thread (new Runnable () {@Overridepublic void run () {thread childthread = new Thread (new Clild Thread ()); Childthread.setdaemon (false); Childthread.start (); System.out.println ("I ' m main thread ...");}); Mainthread.start ();}} Class Clildthread implements runnable{@Overridepublic void Run () {while (true) {System.out.println ("I ' m Child Thread:"); Try{timeunit.milliseconds.sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Operation Result:

I ' m main thread ... I ' m child Thread: I ' m child Thread: I ' m child Thread: I ' m child Thread: I ' m child Thread: (Infinite output)
As you can see, when the main thread ends, Childthread is a non-daemon thread and will execute indefinitely.

The daemon thread has a scenario where, when the main thread ends, the remaining child threads (daemons) are closed automatically, eliminating the hassle of continuing to shut down the child threads. However, bloggers recommend that if there is such a scenario, or the way to achieve more reasonable interruption.

In addition, it is not said that when the child thread is the daemon thread, the thread ends, and the child thread ends, the precondition is that no user thread continues to execute in the current JVM application instance, and if there are other user threads continuing, the background thread will not break, as follows:

Package Com.daemon;import Java.util.concurrent.timeunit;public class Daemonthreadtest{public static void Main (String[ ] args) {thread mainthread = new Thread (new Runnable () {@Overridepublic void run () {thread childthread = new Thread (new Clild Thread ()); Childthread.setdaemon (true); Childthread.start (); System.out.println ("I ' m main thread ...");}); Mainthread.start (); Thread otherthread = new Thread (new Runnable () {@Overridepublic void run () {while (true) {System.out.println ("I ' m The other User thread ... "); Try{timeunit.milliseconds.sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();}}}); O Therthread.start ();}} Class Clildthread implements runnable{@Overridepublic void Run () {while (true) {System.out.println ("I ' m Child Thread:"); Try{timeunit.milliseconds.sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Operation Result:
I ' m other user thread ... I ' m child Thread: I ' m main thread ... I ' m other user thread ... I ' m child Thread: I ' m other user thread ... I ' m child Thread: I ' m child Thread: I ' m other user thread ... I ' m other user thread ... I ' m child Thread: I ' m child Thread: I ' m other user thread ... I ' m other user thread ... I ' m child Thread: I ' m other user thread ... I ' m child Thread: I ' m other user thread ... I ' m child Thread: I ' m other user thread ... I ' m child Thread: I ' m other user thread ... I ' m child Thread: I ' m other user thread ... I ' m child Thread: I ' m other user thread ... I ' m child Thread: (Infinite output)
If you need to end a child thread at the end of the main thread, you can use the following interrupt mode:

Package Com.self;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.timeunit;public class Threadtest{public static void Main (string[] args) {Thread mainthread = new Thread (new Runnable () {public void run () {System.out.println ("Main thread start ..."); Thread sonthread = new Thread (New Thread1 (Thread.CurrentThread ())); Sonthread.setdaemon (false); Sonthread.start (); try {TimeUnit.MILLISECONDS.sleep (10000);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println ("Main thread End");}); Mainthread.start ();}} Class Thread1 implements Runnable{private thread Mainthread;public Thread1 (Thread mainthread) {this.mainthread = Mainthread;} @Overridepublic void Run () {while (mainthread.isalive ()) {System.out.println ("Child thread running ...."); try{ TimeUnit.MILLISECONDS.sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Operation Result:

Main thread start ... Child threads running in .... Child threads running in .... Child threads running in .... Child threads running in .... Child threads running in .... Child threads running in .... Child threads running in .... Child threads running in .... Child threads running in .... Child threads running in .... Child threads running in .... Main thread End

Back to the chase, here are a few things to note:
(1) Thread.setdaemon (true) must be set before Thread.Start () or run out of a illegalthreadstateexception exception. You cannot set a running regular thread as a daemon thread.
(2) The new thread generated in the daemon thread is also daemon.
(3) Do not assume that all applications can be assigned to daemon for service, such as read-write operations or computational logic.

When writing Java multithreaded programming, it is common to prefer to use Java's multi-threaded framework, such as Executorservice, but the Java thread pool will convert the daemon thread to a user thread, so if you want to use a background thread, you cannot use Java's threading pools.

below, the thread pool converts daemon threads into program fragments for user threads:

    Static Class Defaultthreadfactory implements Threadfactory {private static final atomicinteger Poolnumber = NE        W Atomicinteger (1);        Private final Threadgroup Group;        Private final Atomicinteger threadnumber = new Atomicinteger (1);        Private final String Nameprefix;            Defaultthreadfactory () {SecurityManager s = System.getsecuritymanager (); Group = (s! = null)?            S.getthreadgroup (): Thread.CurrentThread (). Getthreadgroup ();        Nameprefix = "pool-" + poolnumber.getandincrement () + "-thread-";                                  Public thread Newthread (Runnable r) {Thread t = new Thread (Group, R,            Nameprefix + threadnumber.getandincrement (), 0);            if (T.isdaemon ()) T.setdaemon (false); if (t.getpriority ()! = thread.norm_priority) t.setpriority(thread.norm_priority);        return t; }    }
Note that this will not only turn the daemon into a user thread, but also turn the priority into thread.norm_priority.

As shown below, the daemon thread is opened with a thread pool:

Package Com.daemon;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.timeunit;public class Daemonthreadtest{public static void Main (string[] args) {Thread Mainthread = New Thread (New Runnable () {@Overridepublic void run () {Executorservice exec = Executors.newcachedthreadpool (); Thread childthread = new Thread (new Clildthread ()); Childthread.setdaemon (true); Exec.execute (Childthread); Exec.shutdown (); System.out.println ("I ' m main thread ...");}); Mainthread.start ();}} Class Clildthread implements runnable{@Overridepublic void Run () {while (true) {System.out.println ("I ' m Child Thread:"); Try{timeunit.milliseconds.sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();}}}}
Operation Result:

I ' m main thread ... I ' m child Thread: I ' m child Thread: I ' m child Thread: I ' m child Thread: I ' m child Thread: I ' m child Thread: I ' m child Thread: I ' m child Thread: I ' m child Thread: (Infinite output)
The code above confirms that the thread pool will turn the daemon thread into a user thread.

As for why JDK will do so, Bo Master has not ponder thorough, if you understand, hope can leave a message to inform.

Java Daemon Threads Overview

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.