In Java, threads are divided into two types: user threads and daemon (service) threads. SetDaemon(false) to the user thread; setDaemon(true) to the daemon thread; if not set, it is the user thread.
To end a single thread, use the Thread.interrupt() method, and to end a multi-thread, you need to set a daemon thread. When no user thread exists, all daemon threads will terminate (it can be understood as: the daemon thread is the service thread, the user thread is the service thread, the user thread (the service thread) is gone, and the service thread will automatically terminate without meaning of existence)
example:
class StopThread implements Runnable {public void run() {// Constructor, while (true) is executed by default during instantiation {// A permanent true loop is used to detect whether the daemon thread will automatically end System.out.println(Thread.currentThread().getName() + "....run");}}} public class threadTest {public static void main(String[] args) {StopThread st = new StopThread();Thread t1 = new Thread(st);// Create a new thread Thread t2 = new Thread(st);t1.setDaemon(true);// Set as a daemon (service) thread. When the user thread is fully hung, all daemon threads will also hang t2.setDaemon(true);t1.start();// Thread starts t2.start();int num = 0;while (true) {if (num++ == 10) {break;}System.out.println(Thread.currentThread().getName() + "......" + num);}System.out.println("over");}}When the last sentence System.out.println("over") is executed, the user thread (main program) ends; the two daemon threads that continuously output information in the backend permanent loop will also automatically terminate.
Another common question is introduced: Is this true if all non-daemon threads in Java end, all daemon threads automatically exit?
Reference answer:
The only function of a daemon thread is to provide services to other threads. When only daemon threads are left, the virtual machine exits” (from: java core technology). Now there are no non-defense, so there is no need for daemon to provide services.
Summarize
The above is the entire content of this article about daemon thread instances in Java language multithreaded termination. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!