欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CountDownLatch用法学习(一)

程序员文章站 2024-03-06 10:19:07
...

场景一:开启一个信号,用来阻止Worker线程在Driver准备就绪前执行。

package com.example.demo20181206;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * @author xichengxml
 * @date 2018/12/7
 * @description
 */
public class CountDownLatchTest {

    @Test
    public void test() throws Exception{
        new Driver().main();
        Thread.sleep(10000);
    }

    class Driver {
        void main() throws InterruptedException {
            CountDownLatch startSignal = new CountDownLatch(1);
            CountDownLatch doneSignal = new CountDownLatch(10);

            // create and start threads
            for (int i = 0; i < 10; i++) {
                new Thread(new Worker(startSignal, doneSignal)).start();
            }
            System.out.println("I am doing something else..."); // don't let run yet
            startSignal.countDown(); // let all threads proceed
            System.out.println("I am still doing something else...");
            doneSignal.await(); // wait for all to finish
        }
    }

    class Worker implements Runnable {
        private CountDownLatch startSignal;
        private CountDownLatch doneSignal;

        public Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
            this.startSignal = startSignal;
            this.doneSignal = doneSignal;
        }

        public void run() {
            try {
                startSignal.await();
                System.out.println("I am working...");
                doneSignal.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}