参考
CS108 handout30
https://blog.youkuaiyun.com/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