java 多線程 join()方法

來源:互聯網
上載者:User
void join()    
    等待該線程終止。    
void join(long millis)    
    等待該線程終止的時間最長為 millis 毫秒。    
void join(long millis, int nanos)    
    等待該線程終止的時間最長為 millis 毫秒 + nanos 納秒。

功能:讓當前線程停止工作,直到插入的線程運行完或經過millis的時間後當前線程才能重新進入可運行狀態。

例子:

public class Join {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Thread t = new Thread(new Runnable() {

   @Override
   public void run() {
    // TODO Auto-generated method stub
    for (int i = 0; i < 30; i++) {
     System.out.println(Thread.currentThread().getName()+" : "+i);
    }
   }
   
  });
  t.start();
  for (int j=0; j<20; j++) {
   if (j == 10)
    try {
     t.join();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   System.out.println(Thread.currentThread().getName() + " : " +j);
  }
 }

}

輸出:

main : 0
main : 1
Thread-0 : 0
Thread-0 : 1
Thread-0 : 2
Thread-0 : 3
Thread-0 : 4
Thread-0 : 5
main : 2
main : 3
Thread-0 : 6
Thread-0 : 7
Thread-0 : 8
main : 4
main : 5
main : 6
main : 7
main : 8
main : 9
Thread-0 : 9
Thread-0 : 10
Thread-0 : 11
Thread-0 : 12
Thread-0 : 13
Thread-0 : 14
Thread-0 : 15
Thread-0 : 16
Thread-0 : 17
Thread-0 : 18
Thread-0 : 19
Thread-0 : 20
Thread-0 : 21
Thread-0 : 22
Thread-0 : 23
Thread-0 : 24
Thread-0 : 25
Thread-0 : 26
Thread-0 : 27
Thread-0 : 28
Thread-0 : 29
main : 10
main : 11
main : 12
main : 13
main : 14
main : 15
main : 16
main : 17
main : 18
main : 19
很明顯的結果,就不作過多解釋了。

 

聯繫我們

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