-
CountDownLatch就是一个计数器,在创建的时候会传入一个初始值,通过countDown()使计数减一,如果调用了await()方法,只有当计数为0时才会放行
public static void main(String[] args) { CountDownLatch countDownLatch = new CountDownLatch(5); for(int i = 1; i <= 5; i++){ new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + "离开教室"); countDownLatch.countDown(); } }, "同学" + i).start(); } try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("所有同学离开教师,班长锁门"); }
-
CyclicBarrier:集齐七颗龙珠即可召唤神龙
public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(7, new Runnable() { @Override public void run() { System.out.println("召唤神龙"); } }); for(int i = 1; i <= 7; i++){ new Thread(() -> { System.out.println(Thread.currentThread().getName() + "已经找到"); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }, "龙珠" + i).start(); } }
-
Semaphore:信号量,+1-1操作。比如你想吃饭就得有筷子(acquire()),要是没筷子只能等别人吃完腾出筷子(release())。
public static void main(String[] args) { //实现两个线程按序打印 //定义两个信号量 Semaphore s1 = new Semaphore(1); Semaphore s2 = new Semaphore(0); // new Thread(() -> { for(int i = 1; i <= 3; i++){ try { s1.acquire(); System.out.println("线程1"); s2.release(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); new Thread(() -> { for(int i = 1; i <= 3; i++){ try { s2.acquire(); System.out.println("线程2"); s1.release(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); }
多线程辅助类CountDownLatch / CyclicBarrier / Semaphore简单入门使用
最新推荐文章于 2024-08-11 20:00:32 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)