Two examples of Java multi-thread daemon

Source: Internet
Author: User
Tags garbage collection sleep

Core note: you can skip this sentence.

The daemon and other threads run at the same time. When all running threads are daemon threads, the Java virtual machine exits.
What is the difference between a daemon thread and a common thread? To call the method setDaemon (true) of a thread object, you can set it as a daemon thread.

Daemon threads are rarely used, but are not useless. For example, JVM garbage collection and memory management threads are all daemon threads. There is also the database connection pool used for database applications. The connection pool also contains many background threads to monitor the number of connections, timeout time, status, and so on.

Detailed description of setDaemon method:

Public final void setDaemon (boolean on) marks this thread as a daemon or user thread. When all running threads are daemon threads, the Java virtual machine exits.
This method must be called before the thread is started.

This method first calls the checkAccess method of the thread without any parameters. This may throw a SecurityException (in the current thread ).

Parameters:
On-if it is true, this thread is marked as a daemon thread.
Throw:
IllegalThreadStateException-if the thread is active.
SecurityException-if the current thread cannot be modified.
For more information, see:

The code is as follows: Copy code
IsDaemon (), checkAccess ()
/**
* Java Thread: thread scheduling-daemon thread
*
* @ Author leizhimin 2009-11-4 9:02:40
*/
Public class Test {
Public static void main (String [] args ){
Thread t1 = new MyCommon ();
Thread t2 = new Thread (new MyDaemon ());
T2.setDaemon (true); // Set it to the daemon thread.
 
T2.start ();
T1.start ();
        }
}
 
Class MyCommon extends Thread {
Public void run (){
For (int I = 0; I <5; I ++ ){
System. out. println ("thread 1" + I + "times! ");
Try {
Thread. sleep (7 );
} Catch (InterruptedException e ){
E. printStackTrace ();
                        }
                }
        }
}
 
Class MyDaemon implements Runnable {
Public void run (){
For (long I = 0; I <9999999L; I ++ ){
System. out. println ("background thread no." + I + "times! ");
Try {
Thread. sleep (7 );
} Catch (InterruptedException e ){
E. printStackTrace ();
                        }
                }
        }
}

The background thread executes 0th times!
Thread 1 executes 0th times!
Thread 1 executes 1st times!
The background thread executes 1st times!
The background thread executes 2nd times!
Thread 1 executes 2nd times!
Thread 1 executes 3rd times!
The background thread executes 3rd times!
Thread 1 executes 4th times!
The background thread executes 4th times!
The background thread executes 5th times!
The background thread executes 6th times!
The background thread executes 7th times!
 
Process finished with exit code 0
The preceding execution results show that:
The foreground thread ensures that the execution is complete, and the background thread exits after the execution is complete.

In fact, the standard for JRE to determine whether the program is executed is that all the frontend thread lines are completed, regardless of the background thread status. Therefore, you must pay attention to this issue when using the background county seat.


Background thread (daemon thread)


The so-called background thread refers to the thread that provides a general service in the background when the program is running, and this thread is not an indispensable part of the program. Therefore, when all non-background threads end, the program will terminate and all background threads will be killed. Conversely, the program will not be terminated as long as any non-background thread (user thread) is still running. The background thread terminates the run method without executing the finally clause. The subthread created by the background thread is also a background thread.
The following is an example of a background thread:

The code is as follows: Copy code
<Span style = "font-size: 16px;"> package demo. thread;
 
Import java. util. concurrent. TimeUnit;
 
Public class DaemonDemo implements Runnable {
@ Override
Public void run (){
Try {
While (true ){
Thread. sleep (1000 );
System. out. println ("#" + Thread. currentThread (). getName ());
            } 
} Catch (InterruptedException e ){
E. printStackTrace ();
} Finally {// The background thread does not execute the finally clause
System. out. println ("finally ");
        } 
    } 
 
Public static void main (String [] args ){
For (int I = 0; I <10; I ++ ){
Thread daemon = new Thread (new DaemonDemo ());
// The background thread must be set before start
Daemon. setDaemon (true );
Daemon. start ();
        } 
System. out. println ("All daemons started ");
Try {
TimeUnit. MILLISECONDS. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
        } 
    } 

</Span>

 
Running result:
All daemons started
# Thread-2
# Thread-3
# Thread-1
# Thread-0
# Thread-9
# Thread-6
# Thread-8
# Thread-5
# Thread-7
# Thread-4
Analysis: From the results, we can see that the ten sub-threads do not print wireless loops. Instead, after the main thread (main () exits, the JVM forces to close all background threads. There is no desired confirmation form, for example, the finally clause is not executed.

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.