Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.spell.threads;
- import java.util.concurrent.CountDownLatch;
- public class CountDownLatchTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // 构造参数为1,可以作为开始开关,只有等他countDown后才开始处理所有的线程
- CountDownLatch start = new CountDownLatch(1);
- CountDownLatch done = new CountDownLatch(5);
- Worker wk = new Worker(start, done);
- for (int i = 0; i < 5; i++) {
- new Thread(wk).start();
- }
- System.out
- .println(System.currentTimeMillis() + " all thread has start");
- // 发送开始信号,通知所有线程该工作了
- start.countDown();
- try {
- // 等待所有的线程工作完成
- done.await();
- System.out.println(System.currentTimeMillis()
- + " all thread has done");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- class Worker implements Runnable {
- private final CountDownLatch start;
- private final CountDownLatch done;
- Worker(CountDownLatch start, CountDownLatch done) {
- this.start = start;
- this.done = done;
- }
- public void run() {
- try {
- // 阻塞,等待开始信号
- start.await();
- doWork();
- // 发送线程完成信号
- done.countDown();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- // 工作的任务就睡打个盹
- public void doWork() {
- // 产生个随机数
- Double d = Math.random() * 1000L;
- Long sleepTime = d.longValue();
- try {
- // 睡觉
- Thread.sleep(sleepTime);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- // 睡晚了报告时间
- System.out.println(Thread.currentThread().getName() + " sleep "
- + sleepTime + " seconds");
- }
- }
Add Comment
Please, Sign In to add comment