CountDownLatch和CyclicBarrier简单使用

CountDownLatch:一般是阻塞主线程,等待其他子线程全部完成后,再继续执行主线程。调用 latch.await() 方法的线程处于阻塞状态,latch.countDown() 达到一定的次数就会唤醒被阻塞的线程。
CyclicBarrier:调用 barrier.await() 方法的线程处于阻塞状态、相互等待,barrier.await() 方法被调用达到一定的数量后,被阻塞的线程一起执行任务。

下面是CountDownLatch和CyclicBarrier组合使用,模拟并发:

public class CountDownLatchAndCyclicBarrier extends Thread {
    private CyclicBarrier barrier;
    private CountDownLatch latch;
    private static int num;

    CountDownLatchAndCyclicBarrier(CyclicBarrier barrier, CountDownLatch latch) {
        this.barrier = barrier;
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            barrier.await(); // 创建好的线程都会在此阻塞、直到 barrier.await() 被调用20次
            for (int i = 0; i < 10000; i++) {
                add();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            latch.countDown(); // 所有线程都执行完此方法,主线程才能被唤醒
        }
    }

    // 有【static】是类锁、所有线程共享一把锁;没有【static】是对象锁、一个对象一把锁、不安全,感兴趣的人可以去掉试试看。
    private static synchronized void add() {
        num++;
    }

    public static void main(String[] args) throws Exception {
        int count = 20;
        CyclicBarrier barrier = new CyclicBarrier(count);
        CountDownLatch latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            new CountDownLatchAndCyclicBarrier(barrier, latch).start();;
        }
        latch.await(); // 阻塞主线程,等待20个线程全部结束
        System.out.println(CountDownLatchAndCyclicBarrier.num);
    }
}

下面是CyclicBarrier模拟运动员准备、起跑、结束的过程:

public class CyclicBarrierTest {
	public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
		ExecutorService executor = Executors.newFixedThreadPool(3);
		CyclicBarrier start = new CyclicBarrier(3); // 三个选手,三个起跑栅栏
		CyclicBarrier end = new CyclicBarrier(4);	// 三个选手栅栏 + 一个结束标志栅栏

		while (true) {
			executor.execute(new Player(start, end, "张三"));
			executor.execute(new Player(start, end, "李四"));
			executor.execute(new Player(start, end, "王五"));

			end.await();
			System.out.println("比赛结束==================================");
		}
	}
}
public class Player extends Thread {

	private CyclicBarrier start;
	private CyclicBarrier end;
	private String name;

	public Player(CyclicBarrier start, CyclicBarrier end, String name) {
		this.start = start;
		this.end = end;
		this.name = name;
	}

	@Override
	public void run() {
		try {
			int a = new Random().nextInt(5) + 1;
			System.out.println(this.name + " 准备耗时: " + a + "s");
			Thread.sleep(a * 1000);

			System.out.println(this.name + " 准备好了。。。 等待其他人。。。");
			this.start.await();

			System.out.println(this.name + " 开始起跑。。。go go go");
			int b = new Random().nextInt(5) + 2;
			Thread.sleep(b * 1000);

			System.out.println(this.name + " 到达终点!!!  耗时: " + b + "s");
			this.end.await();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值