CountDownLatch 的小栗子

53 阅读1分钟
public static void main(String[] args) throws InterruptedException {
    final CountDownLatch countDownLatch = new CountDownLatch(2);
    System.out.println("开始做题...");

    Thread thread1 = new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(5000);
                System.out.println("学生1完成任务");
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });


    Thread thread2 = new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(2000);
                System.out.println("学生2完成任务");
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });


    Thread thread3 = new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(10*1000);
                for (long i = 0; i < countDownLatch.getCount(); i++) {
                    countDownLatch.countDown();
                }

                System.out.println("超时 全部交卷");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    thread1.start();
    thread3.start();

    thread2.interrupt();

    //阻塞并等待全部完成
    countDownLatch.await();
    System.out.println("【全部学生】完成任务");

}