package com.pa.test.JUC.support;
import java.util.concurrent.CountDownLatch;
/**
* CountDownLatch 减法计数器
* 原理:
* countDownLatch.countDown(); //数量-1
* countDownLatch.await(); //执行等待 等待计数器归零,然后在向下执行
* 每次有线程调用countDownLatch.countDown()数量-1 ,当计数器为0 , countDownLatch.await()就会被唤醒,继续执行
*/
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
//计数 总数为6
int a = 6;
CountDownLatch countDownLatch = new CountDownLatch(a);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
//执行减一
System.out.println(Thread.currentThread().getName());
countDownLatch.countDown();
},String.valueOf(i)).start();
}
//执行等待 等待计数器归零,然后在向下执行
countDownLatch.await();
System.out.println("go out");
}
}
package com.pa.test.JUC.support;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("开始");// 先执行7次,cyclicBarrier.await()执行结束,才执行开始
});
for (int i = 1; i <= 7; i++) {
final int temp = i;
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "打印" + temp + "temp");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
package com.pa.test.JUC.support;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* 原理:
* semaphore.acquire() 获得 ,假如已经满了,等待,被释放为止
* semaphore.release() 释放, 会将当前的信号释放+1, 然后喊醒等待线程
* 作用 : 多个线程资源互斥的作用, 并发限流, 控制最大的线程数
*/
public class SemaphoreTest {
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();
}
semaphore.release();
},String.valueOf(i)).start();
}
}
}