015.4 daemon thread and join, 015.4 daemon thread join
Content: daemon thread and join method
##################### Daemon thread
The setDaemon () method is called before the thread is enabled to become a background thread. After the foreground thread runs, the background thread automatically ends.
######## Example
Class Demo implements Runnable {private boolean flag = true; public synchronized void run () {while (flag) {try {wait (); // t1 t2} catch (InterruptedException e) {System. out. println (Thread. currentThread (). toString () + "..... "+ e. toString (); changeFlag ();} System. out. println (Thread. currentThread (). getName () + "----->") ;}// modify the tag. Public void changeFlag () {flag = false;} class StopThreadDemo {public static void main (String [] args) {Demo d = new Demo (); thread t1 = new Thread (d, "wangcai"); Thread t2 = new Thread (d, "Xiaoqiang"); t1.start (); // mark t2 as a background Thread, daemon thread. // T2.setDaemon (true); t2.start (); int x = 0; while (true) {if (++ x = 50) // The condition is met. {// D. changeFlag (); // change the mark of the thread task code to end other threads. // Clear the interrupt state of the t1 thread object and force it to return to the running state. T1.interrupt (); // clears the interrupt state of the t2 thread object and forces it to return to the running state. T2.interrupt (); break; // jumps out of the loop and the main thread can end.} System. out. println ("main -------->" + x);} System. out. println ("over ");}}View Code
################# Join method
When a thread is called, the whole process will end after the thread ends.
1 class Demo implements Runnable 2 {3 4 public void run () 5 {6 for (int x = 1; x <= 40; x ++) 7 {8 System. out. println (Thread. currentThread (). getName () + "------>" + x); 9 Thread. yield (); // temporarily pause the thread. Release the execution right so that other threads can obtain the execution right. 10} 11} 12 13} 14 15 class JoinThreadDemo 16 {17 public static void main (String [] args) 18 {19 Demo d = new Demo (); 20 Thread t1 = new Thread (d); 21 Thread t2 = new Thread (d); 22 23 t1.start (); 24 t2.start (); 25 // The main Thread is executed here, knowing that t1 is to be added for execution, the main thread has released the execution right, 26 // The execution qualification is frozen, and when will it be restored? Wait until t1 thread is executed. 27 // try {t1.join ();} catch (InterruptedException e) {}// used to temporarily join an operation thread. The program will continue to execute after the thread operation is completed. 28 29 for (int x = 1; x <= 50; x ++) 30 {31 System. out. println ("main ---------->" + x); 32} 33 System. out. println ("over"); 34} 35}View Code
Set priority