Java Thread join() 的用法
阿新 • • 發佈:2019-02-18
原址:http://auguslee.iteye.com/blog/1292203
Java Thread中, join() 方法主要是讓呼叫改方法的thread完成run方法裡面的東西后, 在執行join()方法後面的程式碼。示例:
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()這個語句過後, 輸出的書序是亂的, 加上這個語句過後, 就會按照順序輸出, 從某種意義上說實現了同步。