There are two kinds of threads in a Java thread, one is a user thread and the other is a daemon thread. A daemon thread is a special thread that is automatically destroyed by a daemon thread when there is no non-daemon thread in the process. Today we will learn about the daemon thread in Java using an example.
Examples of daemon threads in Java-Simple use of daemon threads in Java
PackageCom.linux.thread;ImportJava.util.concurrent.TimeUnit; Public classMyThreadextendsThread {Private inti = 0; @Override Public voidrun () {Try { while(true) {i++; System.out.println ("I =" +i); TimeUnit.SECONDS.sleep (1); } } Catch(interruptedexception e) {e.printstacktrace (); } }}
The contents of the subject class of the test are as follows:
PackageCom.linux.thread;ImportJava.util.concurrent.TimeUnit; Public classMythreadrun { Public Static voidMain (string[] args) {Try{MyThread thread=NewMyThread (); Thread.setdaemon (true); Thread.Start (); TimeUnit.SECONDS.sleep (5); System.out.println ("Liberty consists in doing what one desires.");//when the main thread executes this, the daemon stops executing. }Catch(interruptedexception e) {e.printstacktrace (); } }}
The results of one run are as follows:
12 3 4 5 in doing What one desires.
After the main thread execution is destroyed (after all non-daemon threads have finished executing), all daemon threads are automatically destroyed.
Friendship Link
Java Foundation---->java Multi-threaded use (v)