主线程等待子线程结束后再运行

1.join

将子线程插入到主线程中,主线程和子线程合并为顺序执行的线程

 1 public class Test {
 2     public static void main(String[] args) throws Exception {
 3         List<Thread> list = new ArrayList<Thread>();
 4         for(int i=0; i<10; i++){
 5             Thread thread = new Thread(new Runnable(){
 6                 public void run(){
 7                     try {
 8                         Thread.sleep(5*1000);
 9                     } catch (Exception e) {
10                         // TODO: handle exception
11                     }
12                     System.out.println("子线程执行完毕!");
13                 }
14             });
15             list.add(thread);
16             thread.start();
17         }
18         for(Thread thread : list){
19             thread.join();
20         }
21         System.out.println("主线程执行完毕!");
22     }
23 }

2.CountDownLatch

 1 public class Test {
 2     public static void main(String[] args) throws Exception {
 3         List<Thread> list = new ArrayList<Thread>();
 4         final CountDownLatch latch = new CountDownLatch(10);
 5         for(int i=0; i<10; i++){
 6             Thread thread = new Thread(new Runnable(){
 7                 public void run(){
 8                     try {
 9                         Thread.sleep(5*1000);
10                     } catch (Exception e) {
11                         // TODO: handle exception
12                     }
13                     latch.countDown();
14                     System.out.println("子线程执行完毕!");
15                 }
16             });
17             list.add(thread);
18             thread.start();
19         }
20         
21         latch.await();
22         System.out.println("主线程执行完毕!");
23     }
24 }

3.CyclicBarrier

 1 public class Test {
 2     public static void main(String[] args) throws Exception {
 3         List<Thread> list = new ArrayList<Thread>();
 4         final CyclicBarrier cyclic = new CyclicBarrier(10);
 5         for(int i=0; i<10; i++){
 6             new Thread(new Runnable(){
 7                 public void run(){
 8                     try {
 9                         Thread.sleep(5*1000);
10                     } catch (Exception e) {
11                         // TODO: handle exception
12                     }
13                     try {
14                         cyclic.await();
15                     } catch (InterruptedException e) {
16                         // TODO Auto-generated catch block
17                         e.printStackTrace();
18                     } catch (BrokenBarrierException e) {
19                         // TODO Auto-generated catch block
20                         e.printStackTrace();
21                     }
22                     System.out.println("子线程执行完毕!");
23                 }
24             }).start();;
25         }
26         
27         cyclic.await();
28         System.out.println("主线程执行完毕!");
29     }
30 }

猜你喜欢

转载自www.cnblogs.com/zyxiaohuihui/p/11130594.html