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

CountDownLatch、ExecutorService的使用

程序员文章站 2022-03-24 12:37:54
...
public class TestService {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(50);
        //开启一个线程池
        ExecutorService executor = Executors.newCachedThreadPool();
        //执行TestThread里面的run方法
        executor.execute(new TestThread(countDownLatch));
        executor.execute(new TestThread(countDownLatch));
        executor.execute(new TestThread(countDownLatch));
        //线程池不再接受新的任务
        executor.shutdown();
    }
}

  • executor.execute(new TestThread(countDownLatch));这段传入的是一个实现Runnable接口的类,执行的方法则是run方法里面的内容,每一个execute则是开启一个线程
public class TestThread implements Runnable{
    private  CountDownLatch countDownLatch;
    public TestThread( CountDownLatch countDownLatch ){
        this.countDownLatch = countDownLatch;
    }

    public void run() {
        while (countDownLatch.getCount() >0){
            countDownLatch.countDown();
            System.out.println("输出:"+Thread.currentThread()+">>>"+ countDownLatch.getCount());
        }
    }
}

  • CountDownLatch countDownLatch = new CountDownLatch(50);这段是启用一个线程辅助类,传入的参数是一个int类型的计数,在TestThread中的run方法中,每执行一次,通过调用countDownLatch.countDown();方法计数减一,当计数内容为0时,则子线程全部执行完成,此时主线程才能继续往下执行。

输出结果

输出:Thread[pool-1-thread-1,5,main]>>>49
输出:Thread[pool-1-thread-1,5,main]>>>47
输出:Thread[pool-1-thread-1,5,main]>>>46
输出:Thread[pool-1-thread-1,5,main]>>>45
输出:Thread[pool-1-thread-1,5,main]>>>44
输出:Thread[pool-1-thread-1,5,main]>>>43
输出:Thread[pool-1-thread-1,5,main]>>>42
输出:Thread[pool-1-thread-1,5,main]>>>41
输出:Thread[pool-1-thread-1,5,main]>>>40
输出:Thread[pool-1-thread-2,5,main]>>>48
输出:Thread[pool-1-thread-1,5,main]>>>39
输出:Thread[pool-1-thread-2,5,main]>>>38
输出:Thread[pool-1-thread-3,5,main]>>>36
输出:Thread[pool-1-thread-1,5,main]>>>36
输出:Thread[pool-1-thread-3,5,main]>>>34
...

具体用法请google