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 automatically leaves after all its non-daemon threads have left.
Daemon Thread: The daemon is used to serve the user thread, and if no other user thread is running, there is no service object and there is no reason to go on.
2. The 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) To set the daemon thread to be thrown before start, no
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) As mentioned in the 3rd above the exit time node problem, so the following situation will 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 (user-defined threads) that need to be serviced and exits directly.
If you want to execute 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) There is no essential difference between daemon and non-daemon threads, which can be switched from one to the 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 mainly introduces the difference and connection between the daemon and the non-daemon threads.
This chapter is here, thank you.
-----------------------------------
Directory
Understanding java-18.2 Basic Threading Mechanism (5)-daemon thread and non-daemon thread