Java daemon thread Thread.setDaemon(true)

There are two types of threads in Java: user threads and daemon threads.

Set to user thread by Thread.setDaemon(false);

Set it as a daemon thread by Thread.setDaemon(true); if the property is not set, it defaults to a user thread.

The difference between user thread and daemon thread:
1. After the main thread ends, the user thread will continue to run and the JVM survives; after the main thread ends, the status of the daemon thread and JVM is determined by the second item below.

2. If there are no user threads, only daemon threads, then the JVM will end.

Daemon thread :
Definition: Daemon thread -- also known as "service thread", will automatically leave when there is no user thread to serve;
Priority: Daemon thread has a lower priority and is used to provide services for other objects and threads in the system ;
Setting: Set the thread as "daemon thread" through setDaemon(true);
Example: The garbage collection thread is a classic daemon thread. When there are no more running threads in our program, the program will no longer generate garbage, and the garbage collector will have nothing to do, so when the garbage collection thread is the only thread left on the JVM, the garbage collection thread will automatically Leave. It always runs in a low-level state for real-time monitoring and management of recyclable resources in the system.
Life cycle: Daemon is a special process that runs in the background. It is independent of the controlling terminal and periodically performs some kind of task or waits for some event to occur. That is to say, the daemon thread does not depend on the terminal, but depends on the system and "lives and dies" with the system.

 

Class TestThread extends Thread {
    // always true loop thread
    public void run() {            
       for(int i=0;;i++){
           try {
               Thread.sleep(1000);
           } catch (InterruptedException ex) {   }
           System.out.println(i);
        }
    }

    public static void main(String [] args){
        TestThread test = new TestThread();
		
	    // It can be set to false when debugging, then the program is an infinite loop with no exit condition.
        test.setDaemon(true);
        test.start();
		
        System.out.println("isDaemon = " + test.isDaemon());
		
        try {
	        // Accept input, make the program pause here, once user input is received, the main thread ends, and the daemon thread ends automatically
            System.in.read();
        } catch (IOException ex) {
	}
   }
}

 

 

http://blog.csdn.net/xyls12345/article/details/26256693

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326862937&siteId=291194637