Daemon Thread: It can also be understood as a background thread, previously created by the foreground thread.
As long as the thread calls Setdaemon (true), the thread can be marked as a daemon thread.
The foreground background thread runs the same way, getting the CPU execution right.
It's only a little different when it's over.
The foreground thread ends with the Run method, and the thread ends.
The background thread can also end with the Run method, the thread ends, and in another case,
When all foreground threads in the process are ended, the process ends regardless of what state the background thread is in.
The process end relies on the foreground thread.
//demonstrates stopping a thread. classDemoImplementsRunnable {Private BooleanFlag =true; Public synchronized voidRun () {//don't be such a synchronized. Add to run method this has turned into a single thread. Here's what it's meant to do. In order to test wait () while(flag) {Try{wait ();//T1 T2//If you use Notify () must be in the same lock as wait (), then you can only use interrupt () If you are not in the same lock . } Catch(interruptedexception e) {System.out.println (Thread.CurrentThread (). toString ()+"....."+e.tostring ()); Changeflag (); } System.out.println (Thread.CurrentThread (). GetName ()+ "----->"); } } //The method of modifying the tag. Public voidChangeflag () {flag=false; }}classMStopThreadDemo2 { Public Static voidMain (string[] args) {Demo d=NewDemo (); Thread T1=NewThread (d); Thread T2=NewThread (d); T1.start (); //mark the T2 as a background thread, the daemon thread. T2.setdaemon (true);//Mark T2 as a background thread as long as the T1 thread ends no matter what state the T2 thread is in, the entire process will endT2.start (); intx = 0; while(true){ if(++x = = 50){ //D.changeflag ();//change the markup of the thread task code so that other threads also end. //clears the interrupt state of the T1 thread object and forces it to revert to the running state. T1.interrupt (); //clears the interrupt state of the T2 thread object and forces it to revert to the running state. //t2.interrupt ();//this comment off the T2 to the background process, so long as the foreground process ends, regardless of the background process in what state the entire process is over Break;//jump out of the loop, the main thread can end. } System.out.println ("Main-------->" +x); } System.out.println ("Over"); }}
java-Daemon Thread