The example of this article tells the usage of the Java thread's daemon. Share it for everyone for your reference. The specifics are as follows:
Guardian thread (Daemon)
Java has two Thread: "Guardian thread Daemon" and "user thread user".
The examples we have seen before are users. The guardian thread is a thread that "provides universal support in the background", which does not belong to the program ontology.
Literally, it is easy for us to understand the guardian thread as a virtual machine (Virtual Machine) internally, and the user thread is created by itself. This is not the case. Any thread can be "daemon" or "user thread user". They are the same in almost every aspect. The only difference is to judge when the virtual machine leaves:
User thread: Java virtual machines automatically leave after all its non -guardians have left.
Guardian thread: The guardian thread is used to serve the user thread. If there are no other user threads running, there will be no service target, and there is no reason to continue.
The SetDaemon (Boolean On) method can easily set the DAEMON mode of the thread. True is Daemon mode and False is User mode. The SetDaemon (Boolean On) method must be called before the thread starts, and the call when the thread is running will produce abnormalities. The ISDAEMON method will test whether the thread is a guardian thread. It is worth mentioning that when you generate other threads in a guardian thread, then these newly generated threads do not need to set the DAEMON attribute, which will be a guardian thread, and the user thread is the same.
Example: The Java garbage recycling thread we are familiar with is a typical guardian thread. When there is no more running Thread in our program, the program will no longer produce garbage, and the garbage recovery device is fine, so When the garbage recycling thread is the only thread left on the Java virtual machine, the Java virtual opportunity will automatically leave.
Import Java.io.ioException;/*** Law threads automatically leave*/Public Class Testmain4 Extends Thread {Public Testmain4 () {}/*** thread when there is no user thread. At the same time, run*/ public void run () {for (int i = 1; i <= 100; i ++) {try {thread.sleep (100);} Catch (interruptexception ex) {ex.printstacktrace ();} s YSTM. out.println (i);}} Public Static void main (string [] art) {testmain4 test = new testmain4 (); test.SetDaemon (true); Test.start (); n ("isdaemon = " + test.isdaemon ()); try {system.in.read (); // Accept the input to stop the program here. Once the user input is received, the main thread is over, the guard thread is automatically ended} {ex.printstacktrace ();}}}It is hoped that this article is helpful to everyone's Java program design.