Java 多線程 CountDownLatch 試用

簡述: java

使用Java多線程的庫,包括 多線程

ExecutorService線程池, 併發

CountDownLatch線程運行控制(知道全部啓動的線程調用完成後,函數纔會繼續執行) dom


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



輸出: ide

相關文章
相關標籤/搜索