场景描述:
模拟10个线程,并发执行,最后汇总结果
代码:
1package com.jf.service.market.impl; 2 3import java.util.concurrent.CountDownLatch; 4import java.util.concurrent.ExecutorService; 5import java.util.concurrent.Executors; 6 7public class CountDownLatchTest { 8 9 public static void main(String[] args) { 10 int num = 10; 11 long time = System.currentTimeMillis(); 12 ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); 13 final CountDownLatch latch = new CountDownLatch(num); 14 for (int i = 0; i < 10; i++) { 15 cachedThreadPool.execute(new Runnable() { 16 public void run() { 17 try { 18 Thread.sleep(1000); 19 } catch (InterruptedException e) { 20 e.printStackTrace(); 21 } 22 System.out.println(" End=== Thread:"+Thread.currentThread().getId()); 23 latch.countDown(); 24 } 25 }); 26 } 27 try { 28 latch.await(); 29 } catch (InterruptedException e) { 30 e.printStackTrace(); 31 } 32 System.out.println("总共耗时:" + (System.currentTimeMillis()-time)); 33 cachedThreadPool.shutdown(); 34 } 35}
结果展示:
End=== Thread:10
End=== Thread:15
End=== Thread:17
End=== Thread:16
End=== Thread:14
End=== Thread:13
End=== Thread:12
End=== Thread:9
End=== Thread:11
End=== Thread:18
总共耗时:1008