CountDownLatch,Cyclic Barrier,Semaphore

参考
CS108 handout30
https://blog.csdn.net/a347911/article/details/53465445

CountDownLatch

一个thread等待其他的thread。首先创建latch,会开始一个counter,然后用await()设定等待的thread,等待其他thread完成,其他thread需要使用latch.countDown()

static CountDownLatch latch; 

public static void testThreadingSupport(int numThreads) {
	latch = new CountDownLatch(numThreads); // 创建latch
	for(int i=0; i< numThreads; i++) {
		new TestListThread().start(); // 开始一个thread
}
	try {
		latch.await(); // 这句话使得main thread开始等待
	} catch (InterruptedException e) {
	…
	}
}

public void run() {
	… // do stuff
	latch.countDown();
}

Cyclic Barrier

The CyclicBarrier can be used to halt a number of threads until a given number have reached a particular point in their code.
one set signals with countdown but does not block, the other set blocks until the counter hits zero.
通过它可以实现让一组线程等待至某个状态之后再全部同时执行。叫做回环是因为当所有等待线程都被释放以后,CyclicBarrier可以被重用。我们暂且把这个状态就叫做barrier,当调用await()方法之后,线程就处于barrier了。

static CyclicBarrier barrier;
	public static void main(String[] args) {
		barrier = new CyclicBarrier(NUM_THREADS);// cyclicBarrier object
		for(int i=0; i< NUM_THREADS; i++) {
			new TestListThread().start(); // threads start
	}
	System.out.println("Main Thread Done");
}

public void run() {
	// get work done
	System.out.println(getName() + " is working");
	try {
		barrier.await();
	} catch (InterruptedException e) {
	// handle interrupt
	// The thread that is interrupted receives an InterruptedException.
	} catch (BrokenBarrierException e) {
	// handle broken barrier
	// In addition if one thread receives InterruptedException, every other thread waiting on the same barrier will receive a BrokenBarrierException.
	}
	// do whatever needs to get done after synching up
	System.out.println(getName() + " is done");
	}
}

Semaphore

Semaphore可以控同时访问的线程个数,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可。

Semaphores are a natural means of managing access to a limited pool of resources

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值