Java Thread join() 用法

来源:互联网 发布:sem高级优化师认证 编辑:程序博客网 时间:2024/05/22 10:25


Java Thread中, join() 方法主要是让调用该方法的thread完成run方法里面的东西后, 再执行join()方法后面的代码。示例:

  1. class ThreadTesterA implements Runnable {  
  2.   
  3.     private int counter;  
  4.   
  5.     @Override  
  6.     public void run() {  
  7.         while (counter <= 10) {  
  8.             System.out.print("Counter = " + counter + " ");  
  9.             counter++;  
  10.         }  
  11.         System.out.println();  
  12.     }  
  13. }  
  14.   
  15. class ThreadTesterB implements Runnable {  
  16.   
  17.     private int i;  
  18.   
  19.     @Override  
  20.     public void run() {  
  21.         while (i <= 10) {  
  22.             System.out.print("i = " + i + " ");  
  23.             i++;  
  24.         }  
  25.         System.out.println();  
  26.     }  
  27. }  
  28.   
  29. public class ThreadTester {  
  30.     public static void main(String[] args) throws InterruptedException {  
  31.         Thread t1 = new Thread(new ThreadTesterA());  
  32.         Thread t2 = new Thread(new ThreadTesterB());  
  33.         t1.start();  
  34.         t1.join(); // wait t1 to be finished  
  35.         t2.start();  
  36.         t2.join(); // in this program, this may be removed  
  37.     }  
  38. }  


 t1启动后,调用join()方法,直到t1的计数任务结束,才轮到t2启动,然后t2也开始计数任务。可以看到,实例中,两个线程就按着严格的顺序来执行了。

如果t2的执行需要依赖于t1中的完整数据的时候,这种方法就可以很好的确保两个线程的同步性。

0 0
原创粉丝点击