CountDownLatch、CyclicBarrier 和 Semaphore
可以参考JDK1.8的帮助文档。
1、CountDownLatch
package com.cc.add;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//总数是6,
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" Go out");
countDownLatch.countDown();//数量减1
},String.valueOf(i)).start();
}
//等待计数器归零,然后再向下执行
countDownLatch.await();
System.out.println("Close Door");
}
}
运行结果:
1 Go out
2 Go out
3 Go out
4 Go out
5 Go out
6 Go out
Close Door
简单说一下原理:
countDownLatch.countDown();
//数量减1
countDownLatch.await();
//等待计数器归零,然后再向下执行
每次有线程调用countDown()数量减1,假设计数器变为0,countDownLatch.await()就会被唤醒,继续执行。
2、CyclicBarrier
加法计数器
package com.cc.add;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("召唤神龙成功!");
});
for (int i = 1; i <= 7 ; i++) {
final int temp = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集"+temp+"个龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
运行结果:
Thread-0收集1个龙珠
Thread-1收集2个龙珠
Thread-2收集3个龙珠
Thread-3收集4个龙珠
Thread-4收集5个龙珠
Thread-5收集6个龙珠
Thread-6收集7个龙珠
召唤神龙成功!
3、Semaphore
现在我们来模拟一下6辆车,三个车位的状况。
package com.cc.add;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
//6辆车,三个车位
public class SemaphoreDemo {
public static void main(String[] args) {
//线程数量:停车位
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <= 6 ; i++) {
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"抢到车位");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();//释放
}
}).start();
}
}
}
运行结果:
Thread-0抢到车位
Thread-1抢到车位
Thread-2抢到车位
Thread-0离开车位
Thread-3抢到车位
Thread-1离开车位
Thread-4抢到车位
Thread-2离开车位
Thread-5抢到车位
Thread-3离开车位
Thread-4离开车位
Thread-5离开车位
原理:
semaphore.acquire();
获得,假设如果已经满了,等待,等待被释放为止。
semaphore.release();
释放,会将当前信号量释放+1,然后唤醒等待的线程。
作用:多个资源互斥的使用!并发限流,控制最大的线程数!