015.4守護線程和join,015.4守護線程join

來源:互聯網
上載者:User

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

 

設定優先權

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.