1. 程式人生 > >java-守護線程

java-守護線程

wait sys exception dex 單線程 string 對象 interrupt notify

守護線程:也可以理解為後臺線程,之前創建的都是前臺線程。
只要線程調用了setDaemon(true);就可以把線程標記為守護線程。
前臺後臺線程運行時都是一樣的,獲取CPU的執行權執行。
只有結束的時候有些不同。
前臺線程要通過run方法結束,線程結束。
後臺線程也可以通過run方法結束,線程結束,還有另一種情況,
當進程中所有的前臺線程都結束了,這時無論後臺線程處於什麽樣的狀態,都會結束,從而進程會結束。
進程結束依賴的都是前臺線程。

技術分享

//演示停止線程。
class Demo implements Runnable {
    private boolean flag = true
; public synchronized void run() {//不要這麽幹將synchronized加到run方法這已經變成了單線程了這裏是故意這麽做為了測試wait() while(flag) { try { wait();//t1 t2 //如果使用notify()必須和wait()在同一個鎖裏,那如果不在同一個鎖怎麽辦只能用interrupt() } catch (InterruptedException e) { System.out.println(Thread.currentThread().toString()
+"....."+e.toString()); changeFlag(); } System.out.println(Thread.currentThread().getName()+"----->"); } } //對標記的修改方法。 public void changeFlag() { flag = false; } } class MStopThreadDemo2 { 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標記為後臺線程只要t1線程結束不管t2線程處於什麽狀態,整個進程都會結束 t2.start(); int x = 0; while(true){ if(++x == 50){ //d.changeFlag();//改變線程任務代碼的標記,讓其他線程也結束。 //對t1線程對象進行中斷狀態的清除,強制讓其恢復到運行狀態。 t1.interrupt(); //對t2線程對象進行中斷狀態的清除,強制讓其恢復到運行狀態。 //t2.interrupt();//將這個註釋掉將t2改成後臺進程,那麽只要前臺進程結束,不管後臺進程處於什麽狀態整個進程就結束了 break;//跳出循環,主線程可以結束。 } System.out.println("main-------->"+x); } System.out.println("over"); } }

java-守護線程