本文介紹兩種主線程等待子線程的實現方式,以5個子線程來說明:
1、使用Thread的join()方法,join()方法會阻塞主線程繼續向下執行。
2、使用Java.util.concurrent中的CountDownLatch,是一個倒數計數器。初始化時先設置一個倒數計數初始值,每調用一次countDown()方法,倒數值減一,他的await()方法會阻塞當前進程,直到倒數至0。
public class AppMain { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub long start = System.currentTimeMillis() ; System.out.println(); ArrayList<Thread> arrayList = new ArrayList<>(); for(int i = 0;i<100;i++) { myThread m1 = new myThread(); m1.start(); m1.join(); myThread2 m2 = new myThread2(); m2.start(); m2.join(); } long end = System.currentTimeMillis(); long endure = end-start; System.out.println("耗時:"+endure); } }
輸出:
Thread-172 :1111 : 111
Thread-173 :2222 : 222
Thread-174 :1111 : 111
Thread-175 :2222 : 222
Thread-176 :1111 : 111
Thread-177 :2222 : 222
Thread-178 :1111 : 111
Thread-179 :2222 : 222
Thread-180 :1111 : 111
Thread-181 :2222 : 222
Thread-182 :1111 : 111
Thread-183 :2222 : 222
Thread-184 :1111 : 111
Thread-185 :2222 : 222
Thread-186 :1111 : 111
Thread-187 :2222 : 222
Thread-188 :1111 : 111
Thread-189 :2222 : 222
Thread-190 :1111 : 111
Thread-191 :2222 : 222
Thread-192 :1111 : 111
Thread-193 :2222 : 222
Thread-194 :1111 : 111
Thread-195 :2222 : 222
Thread-196 :1111 : 111
Thread-197 :2222 : 222
Thread-198 :1111 : 111
Thread-199 :2222 : 222
耗時:68
如果不采用join()方法的話,會先執行完main線程,子線程繼續執行。則不會正確打印出耗時時間
輸出如下:
Thread-181 :2222 : 222
Thread-182 :1111 : 111
Thread-183 :2222 : 222
Thread-184 :1111 : 111
Thread-185 :2222 : 222
Thread-186 :1111 : 111
Thread-187 :2222 : 222
Thread-188 :1111 : 111
Thread-189 :2222 : 222
Thread-190 :1111 : 111
耗時:68----------------------------------會發現主線程先執行完了
Thread-191 :2222 : 222
Thread-192 :1111 : 111
Thread-193 :2222 : 222
Thread-194 :1111 : 111
Thread-195 :2222 : 222
Thread-196 :1111 : 111
Thread-197 :2222 : 222
Thread-198 :1111 : 111
Thread-199 :2222 : 222