Daemon and non-daemon processes

Source: Internet
Author: User

Recently looking at the multi-threaded timer chapter, found that the application of the daemon thread, the basic knowledge of Java still need to add.

Java is divided into two types of threads: User thread and Daemon thread

A daemon 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.

There is no essential difference between a daemon thread and a user thread: The only difference is the departure of the virtual machine: 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.

Example of a timer code:

import java.util.Date;import java.util.TimerTask;public class MyTask extends TimerTask{ @Override public void run() { System.out.println("任务执行了,时间为:"+new Date());}

Main function

Import Java.util.calendar;import java.util.Date;import Java.util.Timer; public class Test1 {publicstatic void Main (string[] args) {System.out.println ("Current time:" +new  Date ()); Calendar calendar=calendar.getinstance (); Calendar.add (Calendar.  SECOND,10); Date date=calendar.gettime (); MyTask task=New MyTask (); Timer timer=new timer (); timer.schedule (Task,date);}}              

Operation Result:

    当前时间:Sat Jun 03 11:47:40 CST 2017 任务执行了,时间为:Sat Jun 03 11:47:50 CST 2017

Although the task ran out, but the process has not been destroyed, the red state, why this situation?

Can look at the source of the timer

public Timer() {    this("Timer-" + serialNumber());}public Timer(String name) { thread.setName(name); thread.start();}

It can be seen that every time a timer is created, a new thread is started, and the thread that is started is not a daemon thread, so it runs all the time. Change the newly created timer to a daemon thread, changing the code as above:

Import Java.util.calendar;import java.util.Date;import Java.util.timer; public class Test1 {public static void Main (string[] args) {System.out.println (new date ()); Calendar calendar=calendar.getinstance (); Calendar.add (Calendar. Second,10); date date=calendar.gettime (); MyTask task=new mytask (); timer timer=new timer (true); timer.schedule (Task,date);}      

The results of the operation are as follows:

当前时间:Sat Jun 03 11:47:40 CST 2017

The thread that is generated in the daemon thread is also the daemon thread

The following example:

PublicClassDaemonImplementsRunnable {Private thread[] t =New thread[10];@Overridepublic void run () {for ( int i=0; i<t.length; i++) {T[i] = new Thread (new daemonspawn ()); T[i].start (); System.out.println ( "Daemonspawn" + i +  "started.");} for (int i=0; i<t.length; i++) { System.out.println ( "t[" + i +  "].isdaemon () =" + T[i].isdaemon () + while (true) {Thread.yield ();}}}     

Class Daemonspawn:

public class DaemonSpawn implements Runnable {@Overridepublic void run() { while (true) { Thread.yield(); }}}

Main function:

import java.util.concurrent.TimeUnit;public class Test1 {public static void main(String[] args) throws InterruptedException { Thread d = new Thread(new Daemon()); d.setDaemon(true); //必须在启动线程前调用 d.start(); System.out.println("d.isDaemon() = " + d.isDaemon() + "."); TimeUnit.SECONDS.sleep(1);}}

Run results

D.isdaemon () =True. Daemonspawn0 started. Daemonspawn1 started. Daemonspawn2 started. Daemonspawn3 started. Daemonspawn4 started. Daemonspawn5 started. Daemonspawn6 started. Daemonspawn7 started. Daemonspawn8 started. Daemonspawn9 started.t[0].isdaemon () = true.t[1]. Isdaemon () = true.t[2].isdaemon () = true.t[3].isdaemon () = true.t[< Span class= "Hljs-number" >4].isdaemon () = true.t[5].isDaemon ( ) = true.t[6].isdaemon () = true.t[ 7].isdaemon () = true.t[8]. Isdaemon () = true.t[9].isdaemon () = true. Process finished with exit code 0         

If the Mian function is TimeUnit.SECONDS.sleep (1); Comment out, look at the source code of TimeUnit.SECONDS.sleep ():

public void sleep(long timeout) throws InterruptedException { if (timeout > 0) { long ms = toMillis(timeout); int ns = excessNanos(timeout, ms); Thread.sleep(ms, ns); }}

is actually the encapsulation of Thread.Sleep (), which provides a more readable thread pause operation
After commenting, the code runs as follows:

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 above results also show that if the user thread is all out, only the daemon thread is present, and the virtual machine exits.

Daemon and non-daemon processes

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.