Java Daemon Threads Overview

Source: Internet
Author: User

Source: Zhu Xiao


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.

 PackageCom.daemon;ImportJava.util.concurrent.TimeUnit; Public classdaemonthreadtest{ Public Static voidMain (string[] args) {Thread Mainthread =NewThread (NewRunnable () {@Override Public voidRun () {Thread Childthread =NewThread (NewClildthread ()); Childthread.setdaemon (true);                Childthread.start (); System.out.println ("I ' m main thread ...");        }        });    Mainthread.start (); }}classClildthreadImplementsrunnable{@Override Public voidRun () { 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:

 PackageCom.daemon;ImportJava.util.concurrent.TimeUnit; Public classdaemonthreadtest{ Public Static voidMain (string[] args) {Thread Mainthread =NewThread (NewRunnable () {@Override Public voidRun () {Thread Childthread =NewThread (NewClildthread ()); Childthread.setdaemon (false);                Childthread.start (); System.out.println ("I ' m main thread ...");        }        });    Mainthread.start (); }}classClildthreadImplementsrunnable{@Override Public voidRun () { 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:

 PackageCom.daemon;ImportJava.util.concurrent.TimeUnit; Public classdaemonthreadtest{ Public Static voidMain (string[] args) {Thread Mainthread =NewThread (NewRunnable () {@Override Public voidRun () {Thread Childthread =NewThread (NewClildthread ()); Childthread.setdaemon (true);                Childthread.start (); System.out.println ("I ' m main thread ...");        }        });        Mainthread.start (); Thread Otherthread =NewThread (NewRunnable () {@Override Public voidRun () { while(true) {System.out.println ("I ' m other user thread ...");Try{TimeUnit.MILLISECONDS.sleep (1000); }Catch(Interruptedexception e)                    {E.printstacktrace ();        }                }            }        });    Otherthread.start (); }}classClildthreadImplementsrunnable{@Override Public voidRun () { 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:

 Packagecom.self;ImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.Executors;ImportJava.util.concurrent.TimeUnit; Public classthreadtest{ Public Static voidMain (string[] args) {Thread Mainthread =NewThread (NewRunnable () { Public voidRun () {System.out.println ("main thread start ..."); Thread Sonthread =NewThread (NewThread1 (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 (); }}classThread1Implementsrunnable{PrivateThread Mainthread; PublicThread1 (Thread mainthread) { This. Mainthread = Mainthread; } @Override Public voidRun () { while(Mainthread.isalive ()) {System.out.println ("Child threads running in ....");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

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 the daemon thread into a program fragment of the user thread:

Static classDefaultthreadfactoryImplementsthreadfactory {Private Static FinalAtomicinteger Poolnumber =NewAtomicinteger (1);Private FinalThreadgroup Group;Private FinalAtomicinteger Threadnumber =NewAtomicinteger (1);Private FinalString Nameprefix;        Defaultthreadfactory () {SecurityManager s = System.getsecuritymanager (); Group = (s! =NULL) ?        S.getthreadgroup (): Thread.CurrentThread (). Getthreadgroup (); Nameprefix = "pool-"+ poolnumber.getandincrement () +"-thread-"; } PublicThread Newthread (Runnable r) {Thread T =NewThread (Group, R, Nameprefix + threadnumber.getandincrement (), 0) ;if(T.isdaemon ()) T.setdaemon (false);if(T.getpriority ()! = thread.norm_priority) t.setpriority (thread.norm_priority);returnT }}

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:

 PackageCom.daemon;ImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.Executors;ImportJava.util.concurrent.TimeUnit; Public classdaemonthreadtest{ Public Static voidMain (string[] args) {Thread Mainthread =NewThread (NewRunnable () {@Override Public voidRun () {Executorservice exec = Executors.newcachedthreadpool (); Thread Childthread =NewThread (NewClildthread ()); Childthread.setdaemon (true);                Exec.execute (Childthread);                Exec.shutdown (); System.out.println ("I ' m main thread ...");        }        });    Mainthread.start (); }}classClildthreadImplementsrunnable{@Override Public voidRun () { 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.

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.