CountDownLatch减法计数器
public class TestCountDownLatch {
public static void main(String[] args) {
/**
* 闭锁
* 1、CountDownLatch end = new CountDownLatch(N); //构造对象时候 需要传入参数N
* 2、end.await() 能够阻塞线程 直到调用N次end.countDown() 方法才释放线程
* 3、end.countDown() 可以在多个线程中调用 计算调用次数是所有线程调用次数的总和
*/
final CountDownLatch countDownLatch = new CountDownLatch(5);
DownLatch dl = new DownLatch(countDownLatch);
long start = System.currentTimeMillis();
for (int i = 0; i < 5; i++) {
new Thread(dl).start();
}
try {
countDownLatch.await();//阻塞main线程,计数
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
}
}
class DownLatch implements Runnable {
private CountDownLatch countDownLatch;
public DownLatch(CountDownLatch latch) {
this.countDownLatch = latch;
}
@Override
public void run() {
synchronized (this) {
try {
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) {
System.out.println("我是偶数" + i);
}
}
} finally {
countDownLatch.countDown();
}
}
}
}
CyclicBarrier减法计数器
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(17, () -> {
System.out.println("收集舍利子-->线程执行完成");//可以看到这句话在最后(17次后,即i=16后)打印。
});
for (int i = 0; i < 17; i++) {
int finalI = i;
new Thread(() -> {
System.out.println("收集舍利子:" + finalI);
try {
cyclicBarrier.await(); //计数减1
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
Semaphore 信号量
public class CyclicBarrierDemo {
public static void main(String[] args) {
//停车位 --->限流
Semaphore semaphore = new Semaphore(3);
for (int i = 0; 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();//释放
}
}, String.valueOf(i)).start();
}
}
}
运行结果: 可以看到最多三个线程同时抢到车位。
0抢到车位
1抢到车位
2抢到车位
0离开车位
1离开车位
3抢到车位
4抢到车位
2离开车位
5抢到车位
3离开车位
4离开车位
5离开车位