9-6多線程

來源:互聯網
上載者:User

 

做作業的第二題總結出幾種方法:

1、建立類的一個變數,有幾個線程對象,變數就是幾,然後在run()方法裡的try{}catch(InterruptedException e){}語句後面添上一個finally{synchronized(this){this.變數名--;}};這樣來鎖定,當每次執行時都會執行finally,從而變數一直減,當變數減到0時,然後再run()裡面的最後再添加一個判斷if(類名.變數名==0){輸出線程運行完畢!}我覺得這個適合多個線程對象還有同步線程 !

2、在main() 主函數裡面最後寫上一個迴圈,使條件永真,迴圈裡有一個判斷語句,判斷對象的getStatc()是否等於線程結束狀態Thread.State.TERMINATEED,如果等於就輸出線程運行完畢!並且跳出迴圈,當然這種只適合對象比較少的情況。

3、也是在main()函數裡寫上一個try{}catch(InterruptedException e){}語句.直接在try裡面寫上Thread.sleep(time);time是比最長時間的線程都大於等於的;這樣保證他們都執行完以後,再監視一下線程的狀態,當然不確定時間的話就填上一個永真迴圈,跟上面第2種方法一樣;

4、還有一種不符合編程的方法,雖然不符合,但是也能成功,就是直接在run()函數裡的try{}catch(InterruptedException e){}語句後面添上一個判斷語句,看線程的時間是否等於最長時間,當然這種是要前提下知道最長時間的;這個就不太適合用 了。

另外附於我寫的一個例子:

 

class A implements Runnable{

    String str;

    int delay;

    static int n=0;

    public A(String str,int delay){

       this.str=str;

       this.delay=delay;

    }

    public static void main(String[] args) {

       Thread t1=new Thread(new A("A類對象1",1000));

       t1.start();

       Thread t2=new Thread(new A("B類對象1",2000));

       t2.start();

       try {

              Thread.sleep(2000);

               if(t1.getState()==Thread.State.TERMINATED&&t2.getState()==Thread.State.TERMINATED){

                  System.out.println("線程運行完畢 !");

              }

           } catch (InterruptedException e) {

              e.printStackTrace();

           }  

 

    public void run() {

      

       try {

           Thread.sleep(delay);

           System.out.println(str + "\t休眠時間為:" + delay);

       } catch (InterruptedException e) {

           e.printStackTrace();

 

       }

    }

}

 

好就先總結到這兒吧!不知道我寫的你是否都看懂.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.