Java Thread join() 的用法

Java Thread中, join() 方法主要是让调用改方法的thread完成run方法里面的东西后, 在执行join()方法后面的代码。示例:
Java代码  收藏代码
  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()这个语句过后, 输出的书序是乱的, 加上这个语句过后, 就会按照顺序输出,  从某种意义上说实现了同步。

转自:http://auguslee.iteye.com/blog/1292203

原文地址:https://www.cnblogs.com/YangBinChina/p/4580099.html