Java 多线程 CountDownLatch 试用

简述:

使用Java多线程的库,包括

ExecutorService线程池,

CountDownLatch线程运行控制(知道所有启动的线程调用完成后,函数才会继续执行)


[java]  view plain copy 在CODE上查看代码片
  1. package test.anialy.multithread;  
  2.   
  3. import java.util.Random;  
  4. import java.util.concurrent.CountDownLatch;  
  5. import java.util.concurrent.ExecutorService;  
  6. import java.util.concurrent.Executors;  
  7. import java.util.concurrent.atomic.AtomicInteger;  
  8. import java.util.concurrent.atomic.AtomicLong;  
  9.   
  10. import org.junit.Test;  
  11.   
  12. public class MultiThreadCountTest  {  
  13.   
  14.     // 线程处理函数  
  15.     public static void doSomething() {  
  16.         try {  
  17.             Thread.sleep(new Random().nextInt(10));  
  18.         } catch (InterruptedException e) {  
  19.             e.printStackTrace();  
  20.         }  
  21.     }  
  22.   
  23.     @Test   
  24.     public void main() throws Exception {  
  25.         final int currency = 10// 线程池大小  
  26.         ExecutorService service = Executors.newFixedThreadPool(currency);  
  27.   
  28.         final AtomicInteger successThreadCnt = new AtomicInteger(0);  
  29.         final AtomicLong totalCost = new AtomicLong(0);  
  30.   
  31.         int count = 100// 执行次数  
  32.         // 所有线程结束  
  33.         final CountDownLatch block = new CountDownLatch(count);    
  34.   
  35.         for (int i = 0; i < count; i++) {  
  36.             service.execute(new Runnable() {  
  37.                 @Override  
  38.                 public void run() {  
  39.                     try {  
  40.                         long start = System.currentTimeMillis();  
  41.                         // 执行某个函数操作  
  42.                         doSomething();  
  43.                         totalCost.addAndGet(System.currentTimeMillis() - start);  
  44.                         successThreadCnt.incrementAndGet();  
  45.                     } catch (Exception e){  
  46.                         e.printStackTrace();  
  47.                     } finally {  
  48.                         block.countDown();  
  49.                     }  
  50.                 }  
  51.             });  
  52.         }  
  53.   
  54.         block.await();  
  55.   
  56.         System.out.printf("共%s次触发函数doSomething,并发%s,成功%s个,平均耗时: %d ms",  
  57.                 count,  
  58.                 currency,  
  59.                 successThreadCnt.get(),  
  60.                 totalCost.get() / successThreadCnt.get());  
  61.     }  
  62. }  



输出:


你可能感兴趣的:(Java 多线程 CountDownLatch 试用)