倒计时器 - CountDownLatch
注意 await()和 countDown()的调用时机。
public class CountDownLatchDemo { //CountDownLatch相当于CyclicBarrier的一个批次处理,可用于制造并发条件 //代码实现上类似信号量Semaphore private static final int COUNT = 10; private static final CountDownLatch countDownLatch = new CountDownLatch(COUNT); public void exec() { System.out.println("http request executed by " + Thread.currentThread().getName() + "@" + System.currentTimeMillis()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { CountDownLatchDemo countDownLatchDemo = new CountDownLatchDemo(); Thread[] threads = new Thread[COUNT]; for (int i = 0; i < COUNT; i++) { threads[i] = new Thread(() -> { try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } //统一执行方法 countDownLatchDemo.exec(); }); } //各个线程进入ready状态 for (int i = 0; i < COUNT; i++) { Thread.sleep(500); System.out.println("Thread-" + i + " start"); threads[i].start(); countDownLatch.countDown(); } } }
清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己
-- 共勉