CountDownLatch
官方文档解释
| package com.luoKing.aid; |
| |
| import java.util.concurrent.CountDownLatch; |
| |
| |
| public class countDownLatch { |
| public static void main(String[] args) throws InterruptedException { |
| |
| CountDownLatch countDownLatch = new CountDownLatch(10); |
| for (int i = 0; i < 10; i++) { |
| new Thread(()->{ |
| System.out.println(Thread.currentThread().getName()+" go out "); |
| countDownLatch.countDown(); |
| },String.valueOf(i)).start(); |
| } |
| countDownLatch.await(); |
| |
| System.out.println("关门"); |
| |
| } |
| } |
如果没有 countDownLatch.await()方法,由于System.out.println("关门");没有锁的束缚,会先执行,
但我们需要先执行多线程中的方法后,再输出“关门”,所以countDownlatch类起到一个计时阻塞的作用
CyclicBarrier
| package com.luoKing.aid; |
| |
| |
| 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("集齐了"+temp+"颗龙珠"); |
| try { |
| cyclicBarrier.await(); |
| } catch (InterruptedException e) { |
| e.printStackTrace(); |
| } catch (BrokenBarrierException e) { |
| e.printStackTrace(); |
| } |
| }).start(); |
| } |
| |
| } |
| |
| } |
semaphore
| package com.luoKing.aid; |
| |
| import java.util.concurrent.Semaphore; |
| import java.util.concurrent.TimeUnit; |
| |
| |
| |
| 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(); |
| } |
| |
| },String.valueOf(i)).start(); |
| } |
| |
| } |
| |
| |
| } |
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决