Java實現主執行緒等待子執行緒join,CountDownLatch
阿新 • • 發佈:2018-12-11
本文介紹兩種主執行緒等待子執行緒的實現方式,以5個子執行緒來說明:
1、使用Thread的join()方法,join()方法會阻塞主執行緒繼續向下執行。
2、使用Java.util.concurrent中的CountDownLatch,是一個倒數計數器。初始化時先設定一個倒數計數初始值,每呼叫一次countDown()方法,倒數值減一,他的await()方法會阻塞當前程序,直到倒數至0。
join方式程式碼如下:
- package com.test.thread;
- import java.util.ArrayList;
- import java.util.List;
- public class MyThread extends Thread
- {
- public MyThread(String name)
- {
- this.setName(name);
- }
- @Override
- public void run()
- {
- System.out.println(this.getName() + " staring...");
- System.out.println(this.getName() + " end...");
- }
- /**
- * @param args
- */
- public static void main(String[] args)
- {
- System.out.println("main thread starting...");
- List<MyThread> list = new ArrayList<MyThread>();
- for (int i = 1; i <= 5; i++)
- {
- MyThread my = new MyThread("Thrad " + i);
- my.start();
- list.add(my);
- }
- try
- {
- for (MyThread my : list)
- {
- my.join();
- }
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- System.out.println("main thread end...");
- }
- }
執行結果如下:
main thread starting... Thrad 2 staring... Thrad 2 end... Thrad 4 staring... Thrad 4 end... Thrad 1 staring... Thrad 1 end... Thrad 3 staring... Thrad 3 end... Thrad 5 staring... Thrad 5 end... main thread end... CountDownLatch方式程式碼如下:
- package com.test.thread;
- import java.util.concurrent.CountDownLatch;
- public class MyThread2 extends Thread
- {
- private CountDownLatch count;
- public MyThread2(CountDownLatch count, String name)
- {
- this.count = count;
- this.setName(name);
- }
- @Override
- public void run()
- {
- System.out.println(this.getName() + " staring...");
- System.out.println(this.getName() + " end...");
- this.count.countDown();
- }
- /**
- * @param args
- */
- public static void main(String[] args)
- {
- System.out.println("main thread starting...");
- CountDownLatch count = new CountDownLatch(5);
- for (int i = 1; i <= 5; i++)
- {
- MyThread2 my = new MyThread2(count, "Thread " + i);
- my.start();
- }
- try
- {
- count.await();
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- System.out.println("main thread end...");
- }
- }
執行結果如下:
main thread starting... Thread 2 staring... Thread 2 end... Thread 4 staring... Thread 4 end... Thread 1 staring... Thread 1 end... Thread 3 staring... Thread 3 end... Thread 5 staring... Thread 5 end... main thread end...