Daemon threads (Daemon thread)

Source: Internet
Author: User

There are two types of threads in Java: The user thread, the Daemon thread.

A daemon thread is a thread that provides a generic service in the background while the program is running, such as a garbage collection thread that is a competent guardian, and that thread is not an integral part of the program. Therefore, when all non-daemon threads end, the program terminates and kills all the daemon threads in the process. Conversely, the program will not terminate as long as any non-daemon threads are still running.

The only difference between the user thread and the 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, the daemon will have no work to do, there is no need to continue to run the program.

Converting a thread to a daemon can be done by invoking the Setdaemon (true) method of the Thread object. There are a few things to keep in mind when using a daemon thread:

(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) The daemon should never access an intrinsic resource, such as a file or a database, because it will be interrupted at any time, even in the middle of an operation.

code example:

ImportJava.util.concurrent.TimeUnit;/*** Daemon Thread*/ Public classdaemons {/**     * @paramargs *@throwsinterruptedexception*/     Public Static voidMain (string[] args)throwsinterruptedexception {Thread d=NewThread (NewDaemon ()); D.setdaemon (true);//must be called before starting the threadD.start (); System.out.println ("D.isdaemon () =" + D.isdaemon () + "."); TimeUnit.SECONDS.sleep (1); }}   classDaemonspawnImplementsRunnable { Public voidrun () { while(true) {Thread.yield (); }    }}   classDaemonImplementsRunnable {Privatethread[] t =NewThread[10];  Public voidrun () { for(inti=0; i<t.length; i++) {T[i]=NewThread (Newdaemonspawn ());            T[i].start (); System.out.println ("Daemonspawn" + i + "started."); }         for(inti=0; i<t.length; i++) {System.out.println ("t[" + i + "].isdaemon () =" +T[i].isdaemon ()+ "."); }         while(true) {Thread.yield (); }    }}

Operation Result:

D.isdaemon () = True.

Daemonspawn 0 started.

Daemonspawn 1 started.

Daemonspawn 2 started.

Daemonspawn 3 started.

Daemonspawn 4 started.

Daemonspawn 5 started.

Daemonspawn 6 started.

Daemonspawn 7 started.

Daemonspawn 8 started.

Daemonspawn 9 started.

T[0].isdaemon () = True.

T[1].isdaemon () = True.

T[2].isdaemon () = True.

T[3].isdaemon () = True.

T[4].isdaemon () = True.

T[5].isdaemon () = True.

T[6].isdaemon () = True.

T[7].isdaemon () = True.

T[8].isdaemon () = True.

T[9].isdaemon () = True.

The above results show that the new thread generated in the daemon thread is also the daemon thread.

If you set the Timeunit in the Mian function. SECONDS. Sleep (1); Comment out, the result of the operation is as follows:

D.isdaemon () = True.

Daemonspawn 0 started.

Daemonspawn 1 started.

Daemonspawn 2 started.

Daemonspawn 3 started.

Daemonspawn 4 started.

Daemonspawn 5 started.

Daemonspawn 6 started.

Daemonspawn 7 started.

Daemonspawn 8 started.

Daemonspawn 9 started.

The results show that if the user thread is all out of operation, only the daemon thread is present, and the virtual machine exits. The following example also illustrates this problem.

code example:

ImportJava.util.concurrent.TimeUnit;/*** Finally shoud is always run?*/ Public classdaemonsdontrunfinally {/**     * @paramargs*/     Public Static voidMain (string[] args) {Thread T=NewThread (NewAdaemon ()); T.setdaemon (true);    T.start (); }}classAdaemonImplementsRunnable { Public voidrun () {Try{System.out.println ("Start Adaemon ..."); TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {System.out.println ("Exiting via Interruptedexception"); } finally{System.out.println ("This shoud is always run?"); }    }}

Operation Result:

Start Adaemon ...

If T.setdaemon (true) is in the main function, the result of the operation is as follows:

Start Adaemon ...

This shoud is always run?

Daemon threads (Daemon thread)

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.