线程的三个辅助类
Semaphore
1 package com.huo.HelperClass; 2 3 import java.util.concurrent.Semaphore; 4 import java.util.concurrent.TimeUnit; 5 6 /** 7 * @version 1.0 8 * @Author 作者名 9 * @Date 2022/9/13 11:18 10 */ 11 public class SemaphoreDemo { 12 public static void main(String[] args) { 13 //表示可用的资源有三个,true表示开启公平锁 14 Semaphore semaphore = new Semaphore(3,true); 15 16 for (int i = 0; i < 6; i++) { 17 new Thread(()->{ 18 try { 19 //acquire() 获得 20 semaphore.acquire(); 21 System.out.println(Thread.currentThread().getName() + " 抢到了车位"); 22 //表示停车1秒 23 TimeUnit.SECONDS.sleep(1); 24 } catch (InterruptedException e) { 25 e.printStackTrace(); 26 } finally { 27 //release() 释放 28 System.out.println(Thread.currentThread().getName() + " 开走了"); 29 semaphore.release(); 30 31 } 32 33 }).start(); 34 } 35 } 36 }
CyclicBarrier
1 package com.huo.HelperClass; 2 3 import java.util.concurrent.BrokenBarrierException; 4 import java.util.concurrent.CyclicBarrier; 5 6 /** 7 * @version 1.0 8 * @Author 作者名 9 * @Date 2022/9/13 11:09 10 */ 11 public class CyclicBarrierDemo { 12 13 14 public static void main(String[] args) { 15 CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> { 16 System.out.println("召唤神龙"); 17 }); 18 19 for (int i = 0; i < 7; i++) { 20 final int temp = i; 21 22 new Thread(() -> { 23 System.out.println(Thread.currentThread().getName() + temp); 24 //等待线程执行完7条 25 try { 26 //这个await()时表示当所有的线程都调用了这个方法,然后就执行表达式中的内容 27 cyclicBarrier.await(); 28 } catch (InterruptedException e) { 29 e.printStackTrace(); 30 } catch (BrokenBarrierException e) { 31 e.printStackTrace(); 32 } 33 34 }).start(); 35 } 36 37 } 38 }
Counter
1 package com.huo.HelperClass; 2 3 import java.util.concurrent.CountDownLatch; 4 5 /** 6 * @version 1.0 7 * @Author 作者名 8 * @Date 2022/9/13 10:58 9 */ 10 public class CounterDemo { 11 public static void main(String[] args) throws InterruptedException { 12 //表示6个东西 没使用一次减一就少一个 13 CountDownLatch latch = new CountDownLatch(6); 14 15 for (int i = 0; i < 6; i++) { 16 new Thread(()->{ 17 System.out.println(Thread.currentThread().getName() + "Go out"); 18 latch.countDown(); //-1 19 },String.valueOf(i)).start(); 20 } 21 22 //等待计数器归0,然后才向下执行 23 latch.await(); 24 25 //调用如下方法开始倒计时 26 System.out.println("Close door"); 27 28 29 } 30 }
浙公网安备 33010602011771号