ccs

    科技2022-08-08  126

    首先第一个countDownLatch。 这个就类似火箭发射倒计时654321只有到1才可以发射,或者举一个生活中的case就是比如一个教室有6个同学一个班长,班长管着锁门的任务,只有六个同学都走完之后班长才可以锁门。如果这七个人每个人都是一个线程, 那么只有六个线程执行完操作之后第七个线程才能执行任务。 看一个秦一统天下的代码。

    import java.util.Objects; import java.util.concurrent.CountDownLatch; /** * @author Jing * @date 2020/10/4 0004 16:47 */ public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { // 先初始化一个实例,传一个计数的最大值 CountDownLatch countDownLatch = new CountDownLatch(6); for (int i = 1; i <= 6; i++) { new Thread(() -> { // 各个线程做自己的工作 System.out.println(Thread.currentThread().getName() + "国被消灭"); // 做完之后 用这个countDownLatch剪一下 countDownLatch.countDown(); }, Objects.requireNonNull(Country.foreachCountry(i)).getRetMessage()).start(); } // 让主线程等在这里,只有剪完之后主线程才会被唤醒。 countDownLatch.await(); System.out.println("一统六国"); } } public enum Country { // 附上枚举类 One(1, "齐"), Two(2, "楚"), Three(3, "燕"), Four(4, "韩"), Five(5, "赵"), Six(6, "魏"); private Integer retCode; private String retMessage; public Integer getRetCode() { return retCode; } public void setRetCode(Integer retCode) { this.retCode = retCode; } public String getRetMessage() { return retMessage; } public void setRetMessage(String retMessage) { this.retMessage = retMessage; } Country(int key, String value) { this.retCode = key; this.retMessage = value; } public static Country foreachCountry(Integer index) { Country[] countries = Country.values(); for (Country country : countries) { if (country.getRetCode() == index) { return country; } } return null; } }

    CyclicBarrier 集齐七颗龙珠1234567才能召唤神龙,或者七个人开会,来够才能开会,做加法。

    import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * @author Jing * @date 2020/10/5 0005 11:30 */ public class CyclicBarrierDemo { public static void main(String[] args) { // 初始化一个实例,然后第一个参数就是要收集的龙珠数,第二个参数就是收集好后要做的事情。 CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> System.out.println("***")); for (int i = 0; i < 7; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName()+"来了"); try { // 每收集一颗龙珠就让这个线程等着 cyclicBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } },String.valueOf(i)).start(); } } }

    Semaphore 可以理解为抢车位

    import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * @author Jing * @date 2020/10/5 0005 11:52 */ public class SemaphoreDemo { public static void main(String[] args) { Semaphore semaphore = new Semaphore(3, false); for (int i = 0; i < 6; i++) { new Thread(() -> { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName()+"抢到了"); TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName()+"又走了"); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } },String.valueOf(i)).start(); } } }
    Processed: 0.009, SQL: 8