1.java.util.concurrent.CountDownLatch
public class CountDownLatch_ {
@SneakyThrows
public static void main(String[] args) {
//the number of times must be invoked before threads can pass through
CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i = 1; i <= 4; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "同学加入游戏~");
countDownLatch.countDown();
}, String.valueOf(i)).start();
}
//Causes the current thread to wait until the latch has counted down to zero
countDownLatch.await();
System.out.println("5位同学已准备就绪,开始游戏~");
}
}
2.java.util.concurrent.CyclicBarrier (允许一组线程全部等待彼此达到共同屏障点)
//构造方法,达到parties值时,执行屏障动作
public CyclicBarrier(int parties,Runnable barrierAction)
public class CyclicBarrier_ {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(5,
() -> System.out.println("5位同学已准备就绪,开始游戏~")
);
for (int i = 1; i <= 4; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "同学加入游戏~");
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
3.java.util.concurrent.Semaphore (型号量,用于记录资源数)
public class Semaphore_ {
public static void main(String[] args) {
//资源数
Semaphore semaphore = new Semaphore(1);
for (int i = 0; i <= 10; i++) {
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + "线程准备获取资源~");
//获取资源,获取不到,进入阻塞队列等待资源的释放
semaphore.acquire(1);
System.out.println(Thread.currentThread().getName() + "线程获取到资源并开始执行任务~");
TimeUnit.SECONDS.sleep(2);
//释放资源
System.out.println(Thread.currentThread().getName() + "线程释放资源~");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
JUC-JUC辅助类
最新推荐文章于 2023-06-06 13:33:14 发布