1. 程式人生 > >Java多執行緒學習與總結(Join)

Java多執行緒學習與總結(Join)

join()方法的用法:

join()是主執行緒 等待子執行緒的終止。也就是在子執行緒呼叫了 join() 方法後面的程式碼,只有等到子執行緒結束了才能執行。

例子如下:

Java程式碼 複製程式碼 收藏程式碼
  1. public class Test implements Runnable {
  2. private static int a = 0;
  3. public void run() {
  4. for(int i=0;i<10;i++)
  5. {
  6. a = a + i;
  7. }
  8. }
  9. /**
  10. * @param args
  11. * @throws InterruptedException
  12. */
  13. public static void main(String[] args) throws InterruptedException {
  14. Thread t1 = new Thread(new Test());
  15. t1.start();
  16. //Thread.sleep(10);
  17. //t1.join();
  18. System.out.print(a);
  19. }
  20. }
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程式碼 複製程式碼 收藏程式碼
  1. public class Test implements Runnable {
  2. private static int a = 0;
  3. public void run() {
  4. for(int i=0;i<10;i++)
  5. {
  6. a = a + i;
  7. }
  8. }
  9. /**
  10. * @param args
  11. * @throws InterruptedException
  12. */
  13. public static void main(String[] args) throws InterruptedException {
  14. Thread t1 = new Thread(new Test());
  15. t1.start();
  16. //Thread.sleep(10);
  17. t1.join();
  18. System.out.print(a);
  19. }
  20. }
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方法的子執行緒先執行完畢再執行主執行緒餘下的程式碼!