The examples in this article describe Java thread daemon thread (Daemon) usage. Share to everyone for your reference. Specifically as follows:
Daemon Thread (Daemon)
Java has two kinds of thread: "Daemon thread daemon" and "User thread".
The example we've seen before is the user, the daemon is a thread that provides commonality support in the background, and it's not part of the program ontology.
It is literally easy to understand that a daemon thread is created internally by a virtual machine (machine), and the user thread is created by itself. This is not the case, and any thread can be either "Daemon thread daemon" or "User thread". They are the same in almost every way, and the only difference is to determine when the virtual machine leaves:
User thread: The Java Virtual machine automatically leaves after all its non-daemon threads have left.
Daemon Thread: The daemon is used to service the user thread, and if no other user thread is running, there is no service object, and there is no reason to go on.
The Setdaemon (Boolean on) method makes it easy to set the daemon mode of a thread, true to daemon mode, and false to user mode. The Setdaemon (Boolean on) method must be invoked before the thread is started, and an exception is generated when the threads are running. The Isdaemon method tests whether the thread is a daemon thread. It is worth mentioning that when you generate other threads in a daemon, these newly generated threads will be the daemon thread and the user thread, without setting the Daemon property.
Example: the Java garbage collection thread we are familiar with is a typical daemon thread, when there is no more thread running in our program, the program will no longer produce garbage, and the garbage collector will have nothing to do, so when the garbage collection thread is the only remaining thread on the Java Virtual machine, The Java virtual opportunity automatically leaves.
Import java.io.IOException;
/**
* Daemon thread automatically leaves
/public class TestMain4 extends thread {public
TestMain4 () {
}/
* When no user thread is available to service *
* thread's Run method, which will run concurrently with other threads/public
void Run () {for
(int i = 1; I <= i++) {
try {
thread . Sleep (MB);
catch (Interruptedexception ex) {
ex.printstacktrace ();
}
System.out.println (i);
}
}
public static void Main (String [] args) {
TestMain4 test = new TestMain4 ();
Test.setdaemon (true);
Test.start ();
System.out.println ("Isdaemon =" + Test.isdaemon ());
try {
System.in.read ();
Accept input so that the program pauses, once the user input is received, the main thread ends, and the daemon automatically ends the
catch (IOException ex) {
ex.printstacktrace ();
}
}
}
I hope this article will help you with your Java programming.