self-confidence,the source of all the power

导航

java 多线程 join()方法

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
很明显的结果,就不作过多解释了。

 

posted on 2012-08-20 16:41  漩涡鸣人  阅读(475)  评论(0编辑  收藏  举报