CountDownLatchModule 使用

package com.java;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CountDownLatchModule {

//线程数
private static int COUNT_DOWN_LATCH_MODULE=10;

//单位秒
private static int COUNT_DOWN_LATCH_TIMES=5;

public static void main(String[] args) {
    //创建CountDownLatch并设置计数值,该count值可以根据线程数的需要设置
    CountDownLatch countDownLatch=new CountDownLatch(COUNT_DOWN_LATCH_MODULE);
    //创建线程池
    ExecutorService threadPool = Executors.newCachedThreadPool();
    for (int i=0;i<COUNT_DOWN_LATCH_MODULE;i++){
        threadPool.execute(()->{
            try {
                System.out.println(Thread.currentThread().getName()+" current tread name ");
            }catch (Exception e){
                System.out.println("Exception  : current tread  err");
            }finally {
                //线程执行完闭
                countDownLatch.countDown();
            }
        });
    }
    System.out.println("main thread do current-1");

    try {
        countDownLatch.await(COUNT_DOWN_LATCH_TIMES, TimeUnit.MICROSECONDS);
    }catch (InterruptedException exception){
        System.out.println("Exception: await interrupted exception");
    } finally {
        System.out.println("countDownLatch: " + countDownLatch.toString());
    }
    System.out.println("main thread do current-2");
    //若需要停止线程池可关闭;
    threadPool.shutdown();
}

}
class CountDownLatchTest {

/**
 * a start signal that prevents any worker from proceeding
 * until the driver is ready for them to proceed;
 * @param args
 * @throws InterruptedException
 */
public static void main(String[] args) throws InterruptedException {
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(10);
    for (int i = 0; i < 10; i++) {
        // create and start threads
        new Thread(new Worker(startSignal, doneSignal)).start();
    }
    // don't let run yet
    System.out.println("do current else 1");
    // let all threads proceed
    startSignal.countDown();
    System.out.println("do current else 2");
    // wait for all to finish
    doneSignal.await();
    System.out.println("wait for all to finsh");
}

static class Worker implements Runnable{

    private final CountDownLatch startSignal;
    private final CountDownLatch doneSignal;

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

    @Override
    public void run() {
        try {
            startSignal.await();
            doWork();
            doneSignal.countDown();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    void doWork() {
        System.out.println("do work!");
    }
}

}
class CountDownLatchTest2 {

/**
 * a completion signal that allows the driver to wait
 * until all workers have completed.
 * @param args
 * @throws InterruptedException
 */
public static void main(String[] args) throws InterruptedException {
    CountDownLatch doneSignal = new CountDownLatch(5);
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    for (int i = 0; i < 10; i++) {
        // create and start threads
        cachedThreadPool.execute(new Worker(doneSignal, i));
    }
    // don't let run yet
    System.out.println("do current else 1");
    // wait for all to finish
    doneSignal.await();
    System.out.println("======count: " + doneSignal.getCount());
    System.out.println("do current else 2");
    cachedThreadPool.shutdown();
}

static class Worker implements Runnable{

    private final CountDownLatch doneSignal;
    private final int i;

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

    @Override
    public void run() {
        try {
            doWork();
            doneSignal.countDown();
            System.out.println("i = " + i + ", " + doneSignal.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    void doWork() {
        System.out.println("do work!");
    }
}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值