015.4守護線程和join,015.4守護線程join
內容:守護線程、join方法
#####################守護線程
通過開啟線程之前調用setDaemon()方法,變成後台線程,前台線程運行完,後台線程自動會結束
#########例子
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()+"----->"); } } //對標記的修改方法。 public void changeFlag() { flag = false; }}class StopThreadDemo { public static void main(String[] args) { Demo d = new Demo(); Thread t1 = new Thread(d,"旺財"); Thread t2 = new Thread(d,"小強"); t1.start(); //將t2標記為後台線程,守護線程。// t2.setDaemon(true); t2.start(); int x = 0; while(true) { if(++x == 50)//條件滿足。 {// d.changeFlag();//改變線程任務代碼的標記,讓其他線程也結束。 //對t1線程對象進行中斷狀態的清除,強制讓其恢複到運行狀態。 t1.interrupt(); //對t2線程對象進行中斷狀態的清除,強制讓其恢複到運行狀態。 t2.interrupt(); break;//跳出迴圈,主線程可以結束。 } System.out.println("main-------->"+x); } System.out.println("over"); }}View Code
#################join方法
哪個線程調用了,就需要等待該線程結束,整個進程才會結束
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();//線程臨時暫停。將執行權釋放,讓其他線程有機會擷取執行權。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 //主線程執行到這裡,知道t1要加入執行,主線程釋放了執行權,26 //執行資格並處於凍結狀態,什麼時候恢複呢?等t1線程執行完。27 // try{t1.join();}catch(InterruptedException e){}//用於臨時加入一個運算的線程。讓該線程運算完,程式才會繼續執行。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
設定優先權