In this chapter we discuss the daemon and non-daemon threads.
1. What is a daemon thread? What is a non-daemon thread?
Non-daemon thread: The Java Virtual machine voluntarily leaves itself after all its non-daemon threads have left.
Daemon Thread: The daemon is used to serve the user thread, assuming there are no other user threads running, there is no service object and there is no reason to continue.
2. Same point
Everyone is a thread. Can actually switch to each other.
3. Differences: Point in time of exit
Order of Exit:
Daemon thread, non-daemon thread->JVM
4. Note the point:
(1) Set the daemon to not throw an exception before start
Package Com.ray.ch17;public class Test {public static void main (string[] args) {Writepaper writepaper = new Writepaper (); T Hread thread = new Thread (writepaper); Thread.Start (); Thread.setdaemon (True);}} Class Writepaper implements Runnable {@Overridepublic void run () {System.out.println ("Run");}}
Output:
Run
Exception in thread "main" java.lang.IllegalThreadStateException
At Java.lang.Thread.setDaemon (thread.java:1275)
At Com.ray.ch17.Test.main (test.java:9)
(2) The Exit time node problem as mentioned in the 3rd above. As a result, the following conditions may occur
Package Com.ray.ch17;public class Test {public static void main (string[] args) {Writepaper writepaper = new Writepaper (); T Hread thread = new Thread (writepaper); Thread.setdaemon (true); Thread.Start ();}} Class Writepaper implements Runnable {@Overridepublic void run () {System.out.println ("Run");}}
Output:
No
In fact, there is no corresponding statement at all. Because the daemon knows that there are no non-daemon threads that need service today (the user defines the thread), it exits directly.
Suppose you want to run the output inside the program. Do not set the guard:
Package Com.ray.ch17;public class Test {public static void main (string[] args) {Writepaper writepaper = new Writepaper (); T Hread thread = new Thread (writepaper); Thread.Start ();}} Class Writepaper implements Runnable {@Overridepublic void run () {System.out.println ("Run");}}
Output:
Run
(3) The daemon and non-daemon threads are in fact no essential difference, can switch to each other
Package Com.ray.ch17;public class Test {public static void main (string[] args) {Writepaper writepaper = new Writepaper (); T Hread thread = new Thread (writepaper); Thread.setdaemon (true); Thread.setdaemon (false); Thread.Start ();}} Class Writepaper implements Runnable {@Overridepublic void run () {System.out.println ("Run");}}
Output:
Run
Summary: This chapter focuses on the differences and connections between the daemon and the non-daemon threads.
This chapter is here, thank you.
-----------------------------------
Folder
Learn from the java-18.2 main threading mechanism (5)-Daemon and non-daemon threads