Java--JUC--强大的辅助类讲解
- CountDownLatCh的使用(做减法,六个线程都结束,才能完成主线程)
-
package com.model.new_concurrent; import java.util.concurrent.CountDownLatch; class CloseDoor{ public void close(){ System.out.println(Thread.currentThread().getName()+"离开可教室"); } } /** * 实现了一个 等6个进程都完成之后主进程才能结束的逻辑 * CountDownLatch * * */ public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch=new CountDownLatch(6); CloseDoor closeDoor=new CloseDoor(); for (int i=1;i<=6;i++){ new Thread(() ->{ closeDoor.close(); countDownLatch.countDown(); },String.valueOf(i)).start(); } countDownLatch.await(); System.out.println("班长关门了***"); } }
-
- CyclicBarrier工具类的使用:(做加法:需要完成七个进程才能进行下面的进程)
-
package com.model.new_concurrent; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * * * */ public class CyclicBarrierDemo { /** * 实现了 完成7个及龙珠的线程之后才能进行 召唤神龙的线程的 业务逻辑(都是非主线程) * */ public static void main(String[] args) { CyclicBarrier cyclicBarrier=new CyclicBarrier(7,()->{ System.out.println("收集了7颗龙珠,召唤神龙"); }); for (int i=1;i<=7;i++){ final int t=i; new Thread(() ->{ System.out.println(Thread.currentThread().getName()+"线程收集了第"+t+"颗龙珠"); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } },String.valueOf(i)).start(); } } }
-
- Semaphore(红绿灯的使用):多个线程争抢多个资源,
-
package com.model.new_concurrent; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class SemaphoreDemo { /** * 用于实现多个线程,争抢多个资源的情况(限流) * 当资源数量为1是,就像相当于在资源类中加锁一样的情况 * */ 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(3); semaphore.release(); System.out.println(Thread.currentThread().getName()+"使用完毕 ,释放了资源"); } catch (InterruptedException e) { e.printStackTrace(); } },String.valueOf(i)).start(); } } }
-