主子线程

本文介绍两种主线程等待子线程的实现方式,以5个子线程来说明:

1、使用Thread的join()方法,join()方法会阻塞主线程继续向下执行。

2、使用Java.util.concurrent中的CountDownLatch,是一个倒数计数器。初始化时先设置一个倒数计数初始值,每调用一次countDown()方法,倒数值减一,他的await()方法会阻塞当前进程,直到倒数至0。

本例中 主线程不光能和子线程 协同步调 也可以添加static变量 进行通讯

join方式代码如下:

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. package com.test.thread;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. public class MyThread extends Thread  
  7. {  
  8.   
  9.     public MyThread(String name)  
  10.     {  
  11.         this.setName(name);  
  12.     }  
  13.   
  14.     @Override  
  15.     public void run()  
  16.     {  
  17.         System.out.println(this.getName() + " staring...");  
  18.   
  19.         System.out.println(this.getName() + " end...");  
  20.     }  
  21.   
  22.     /** 
  23.      * @param args 
  24.      */  
  25.     public static void main(String[] args)  
  26.     {  
  27.         System.out.println("main thread starting...");  
  28.   
  29.         List<MyThread> list = new ArrayList<MyThread>();  
  30.   
  31.         for (int i = 1; i <= 5; i++)  
  32.         {  
  33.             MyThread my = new MyThread("Thrad " + i);  
  34.             my.start();  
  35.             list.add(my);  
  36.         }  
  37.   
  38.         try  
  39.         {  
  40.             for (MyThread my : list)  
  41.             {  
  42.                 my.join();  
  43.             }  
  44.         }  
  45.         catch (InterruptedException e)  
  46.         {  
  47.             e.printStackTrace();  
  48.         }  
  49.   
  50.         System.out.println("main thread end...");  
  51.   
  52.     }  
  53.   
  54. }  

运行结果如下:

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...

原文地址:https://www.cnblogs.com/lnas01/p/5948336.html