1.CyclicBarrier
[1].概念
CyclicBarrier和CountDownLatch的概念相反。
注:对于CountDownLatch不熟悉的小伙伴可以前往我的另一篇文章了解:juejin.cn/post/689012…
CountDownLatch从一个大于0的整数开始算起,每个线程减1, 减为0后才能执行主线程。而CyclicBarrier是从0开始, 计时到某一个特定的整数后,才会执行主线程。
CyclicBarrier就好比集齐7颗龙珠, 才能召唤神龙。
[2].使用
代码如下:
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier=new CyclicBarrier(7,()->{
System.out.println("Summon the Dragon");
});
for (int i = 0; i < 7; i++) {
final int num=i;
new Thread(()->{
System.out.println("Thread "+Thread.currentThread().getName()+" collect "+(num+1)+" dragon ball");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
结果:
Thread 0 collect 1 dragon ball
Thread 3 collect 4 dragon ball
Thread 2 collect 3 dragon ball
Thread 1 collect 2 dragon ball
Thread 4 collect 5 dragon ball
Thread 5 collect 6 dragon ball
Thread 6 collect 7 dragon ball
Summon the Dragon
由结果我们可以发现,在执行完所有其他线程之后,才会执行主线程。
2.Semaphore
[1].概念
CountDownLatch的问题是不能复用。比如count=3,那么加到3,就不能继续操作了。
而Semaphore可以解决这个问题,比如去餐馆吃饭,餐馆里只有5个位置,但却来了8个人。对于CountDownLatch只能服务5个人,而Semaphore可以服务8个。位置空出来后,其它人可以过去使用,这就涉及到了Semaphore.accquire()和Semaphore.release()方法。
[2].使用
代码:
public class SemaphoreDemo {
public static void main(String[] args) {
//The capacity of semaphore has been set to 5
Semaphore semaphore = new Semaphore(5);
for (int i = 0; i < 8; i++) {
final int num = i;
new Thread(() -> {
try {
//ask one slot to fit in to have the meal for 3s
semaphore.acquire();
System.out.println("Person(thread) " + Thread.currentThread().getName() + " is having meal.");
TimeUnit.SECONDS.sleep(3);
System.out.println("Person(thread) " + Thread.currentThread().getName() + " finished.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//the person who fitted in has to leave to release the slot
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
结果:
Person(thread) 1 is having meal.
Person(thread) 4 is having meal.
Person(thread) 3 is having meal.
Person(thread) 0 is having meal.
Person(thread) 2 is having meal.
Person(thread) 3 finished.
Person(thread) 2 finished.
Person(thread) 5 is having meal.
Person(thread) 4 finished.
Person(thread) 0 finished.
Person(thread) 1 finished.
Person(thread) 7 is having meal.
Person(thread) 6 is having meal.
Person(thread) 5 finished.
Person(thread) 7 finished.
Person(thread) 6 finished.
由结果可知,当最开始来的5个人用餐完毕之后,只要里面走了一个人之后,另外等待的三个人就会进来用餐。
如果你觉得这篇文章对你有所帮助,请留个言或点个赞吧!