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

CountDownLatch用法学习(二)

程序员文章站 2024-03-06 09:57:55
...

场景:等到所有worker线程执行完成后,让driver执行动作

package com.example.demo20181206;

import org.junit.Test;

import java.util.concurrent.*;

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

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

    class Driver {
        void main() throws InterruptedException {
            CountDownLatch doneSignal = new CountDownLatch(10);
            Executor executor = new ThreadPoolExecutor(4, 32, 15, TimeUnit.MINUTES, new LinkedBlockingDeque<>(100));
            for (int i = 0; i < 10; i++) { // create and start threads
                executor.execute(new Worker(doneSignal, i));
            }
            doneSignal.await(); // wait for all to finish
            System.out.println("I am wating you all to finish");
        }
    }

    class Worker implements Runnable {
        private CountDownLatch doneSignal;
        private int i;

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

        public void run() {
            System.out.println("I am working..." + i);
            doneSignal.countDown();
        }
    }
}