常用的辅助类(必会)

1.CountDownLatch

常用的辅助类(必会)_第1张图片

package com.kuang.add;

import java.util.concurrent.CountDownLatch;

//计数器  减法
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        //总数是6,必须要执行任务的时候,再使用
        CountDownLatch countDownLatch = new CountDownLatch(6);

        for (int i = 0; i < 6; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    System.out.println(Thread.currentThread().getName()+" Go Out");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();
        }
        countDownLatch.await();//等待计数器归零,然后再向下执行
        System.out.println("close Door");

    }


}

常用的辅助类(必会)_第2张图片

2.CyclicBarrier

常用的辅助类(必会)_第3张图片

package com.kuang.add;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {
    public static void main(String[] args) {
        /**
         * 集齐7颗龙珠 召唤神龙
         */
        //召唤龙珠的线程
    CyclicBarrier cyclicBarrier= new CyclicBarrier(7,()->{
        System.out.println("召唤神龙成功");
        });

        for (int i = 0; i < 6; i++) {
            int finalI = i;
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"收集了"+ finalI+"个龙珠");
                try {
                    cyclicBarrier.await();//等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }

            }).start();

        }

    }

}

 

3.Semaphore

Semaphore :信号量

package com.kuang.add;

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 = 0; i < 6; i++) {

            new Thread(()->{
                //acquire()得到许可
                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();//release()  释放
                }

            },String.valueOf(i)).start();
        }
    }
}

原理:

semaphore.acquire(); 获得,假设如果已经满了,等待,等待被释放为止!
semaphore.release(); 释放,会将当前的信号量释放+1,然后唤醒等待线程!

作用:多个共享资源互斥的使用!并发限流。控制最大的线程数!

你可能感兴趣的:(JUC,java,算法,开发语言)