Java多執行緒學習與總結(Join)
阿新 • • 發佈:2018-11-01
join()方法的用法:
join()是主執行緒 等待子執行緒的終止。也就是在子執行緒呼叫了 join() 方法後面的程式碼,只有等到子執行緒結束了才能執行。
例子如下:
Java程式碼- public class Test implements Runnable {
- private static int a = 0;
- public void run() {
- for(int i=0;i<10;i++)
- {
- a = a + i;
- }
- }
- /**
- * @param args
- * @throws InterruptedException
- */
- public static void main(String[] args) throws InterruptedException {
- Thread t1 = new Thread(new Test());
- t1.start();
- //Thread.sleep(10);
- //t1.join();
- System.out.print(a);
- }
- }
public class Test implements Runnable { private static int a = 0; public void run() { for(int i=0;i<10;i++) { a = a + i; } } /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new Test()); t1.start(); //Thread.sleep(10); //t1.join(); System.out.print(a); } }
上面程式最後的輸出結果是0,就是當子執行緒還沒有開始執行時,主執行緒已經結束了。
Java程式碼- public class Test implements Runnable {
- private static int a = 0;
- public void run() {
- for(int i=0;i<10;i++)
- {
- a = a + i;
- }
- }
- /**
- * @param args
- * @throws InterruptedException
- */
- public static void main(String[] args) throws InterruptedException {
- Thread t1 = new Thread(new Test());
- t1.start();
- //Thread.sleep(10);
- t1.join();
- System.out.print(a);
- }
- }
public class Test implements Runnable {
private static int a = 0;
public void run() {
for(int i=0;i<10;i++)
{
a = a + i;
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Test());
t1.start();
//Thread.sleep(10);
t1.join();
System.out.print(a);
}
}
上面程式的執行結果是45,就是當主執行緒執行到t1.join()時,先執行t1,執行完畢後在執行主執行緒餘下的程式碼!
總結:join()方法的主要功能就是保證呼叫join方法的子執行緒先執行完畢再執行主執行緒餘下的程式碼!