Java Thread中, join() 方法是让调用该方法的主线程执行run()时暂时卡住,等run()执行完成后, 主线程再调用执行join()后面的代码。示例:
1class 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 15class 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 29public 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()这个语句过后, 输出的顺序是乱的, 加上这个语句后, 就会按照顺序输出, 从某种意义上说实现了同步。