4.3.5 并发工具类

AQS

在这里插入图片描述### 实现AQS的方法可以实现对应的锁
在这里插入图片描述

Semaphore

在这里插入图片描述

public class Semaphore_Demo {
//     static KaneSemaphore sp =new KaneSemaphore(6);
     static Semaphore=new Semaphore(6);


    public static void main(String[] args) {
        for (int i = 0; i <1000 ; i++) {
            new Thread(()->{
                    sp.acquire(); //就是拿信号量

                System.out.println("当前信号量限制....");
                try {
                    Thread.sleep(2000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("执行完了");
                sp.release(); //执行完了,就释放信号量
            }).start();
        }
    }
}

public class KaneSemaphore {

    private Sync sync;

    public KaneSemaphore(int permits) {
     sync = new Sync(permits);
    }

    public void acquire(){
       sync.acquireShared(1);
    }

    public void release(){
        sync.releaseShared(1);

    }




    class Sync extends AbstractQueuedSynchronizer{
       private int permits;

        public Sync(int permits) {
            this.permits = permits;
        }

        @Override
        protected int tryAcquireShared(int arg) {
            //定义自己的方法
            int state = getState();
            int nextState = state + arg;

            if(nextState <= permits){
                if(compareAndSetState(state,nextState))
                return 1;
            }
            return -1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            int state = getState();
            if(compareAndSetState(state,state-arg)){
                return true;
            }else{
                return false;
            }

        }
    }
}

CountDownLatch

多个任务成功之后 一起执行
在这里插入图片描述

public class CountDownLatch_Demo {

    public static void main(String[] args) throws InterruptedException {
        KaneCountDownLatch latch = new KaneCountDownLatch(6); //计数为6


        for (int i = 0; i <6 ; i++) {
            new Thread(()->{
                System.out.println("开始准备.....");
                latch.countDown();//计数减一
            }).start();
            Thread.sleep(1000);
        }

        latch.await(); //每个线程执行一次,则-1,在latch为0的时候开始向下运行 这是这些线程都准备就绪,然后去一起干同一件事

        //还有一种方式, 将一个活分为多段,每个线程去干一段
//        for (int i = 0; i <6 ; i++) {
//            new Thread(()->{
//                  latch.countDown(); // 计数减一
//                try {
//                    latch.await(); // 阻塞 -- > 0
//                    System.out.println("线程:"+Thread.currentThread().getName()+"执行完毕");
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }).start();
//        }

        System.out.println("开始干活....");
    }
}

public class KaneCountDownLatch {

    private Sync sync;

    public KaneCountDownLatch(int count) {
        sync = new Sync(count);
    }

    public void countDown(){
       sync.releaseShared(1);
    }

    public  void await(){
       sync.acquireShared(1);
    }



    class Sync extends AbstractQueuedSynchronizer{

        public Sync(int count) {
            setState(count);
        }


        @Override
        protected int tryAcquireShared(int arg) {
            return getState()==0?1:-1;
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            while (true){
                int c = getState();
                if(c==0)
                    return false;
                int nextc = c -1;
                if(compareAndSetState(c,nextc)){
                    return nextc==0;
                }
            }
        }
    }
}


CyclicBarrier

在这里插入图片描述

public class CyclicBarrier_Demo {

    public static void main(String[] args) throws InterruptedException {
        KaneCyclicBarrier barrier = new KaneCyclicBarrier(4);

        for (int i = 0; i <100 ; i++) { //假设有100个任务,每次只能有固定数量的线程去执行,可以使用这个
            new Thread(()->{

                    barrier.await();
                    System.out.println("任务开始执行");

             }).start();
             Thread.sleep(500L);
         }
    }
}

public class KaneCyclicBarrier {

    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    private int count =0; //批次

    private final int parties; //多少线程准备就绪?

    private Object generation = new Object();

    public KaneCyclicBarrier(int parties) {
        this.parties = parties;
    }



    public  void await(){
        final ReentrantLock lock = this.lock;
        lock.lock();
       try {
            final  Object g = generation;

           int index = ++count;
           if (index == parties) {
             nextGeneration();
             return;
           }

           while (true) {
               try {
                   condition.await();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }

               if(g!=generation){
                   return;
               }
           }
       }finally {
           lock.unlock();
       }
    }

    public void nextGeneration(){
        condition.signalAll();
        count=0;
        generation = new Object();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值