CountDownLatch 、ReentryLock、CyclicBarrier 、ReadWriteLock 、Semaphore、Exchanger、LockSupport

CountDownLatch

又叫门栓,初始化设置一个值,当这个值等于0时,是否锁

 private void countDownLatch(){
        CountDownLatch countDownLatch = new CountDownLatch(1);
       try {
           countDownLatch.await();//加锁
       } catch (InterruptedException e) {
           e.printStackTrace();
       }

       countDownLatch.countDown();//数量减一,数据为0时,释放锁
   }

ReentryLock/Condition

condition本质就是等待队列
这个条件可以帮忙调用await和signal方法

public class MyContainer2<T> {
    private LinkedList<T> lists = new LinkedList<>();
    private Integer MAX = 10;
    private Integer count = 0;

    private Lock lock = new ReentrantLock();
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();


    private  void put(T t){
        try{
            lock.lock();
            while (lists.size()== MAX){
                try {
                    producer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            lists.add(t);
            System.out.println("put:" +t);
            count++;
            consumer.signalAll();
        }finally {
            lock.unlock();
        }

    }

    private  T get(){
        T t = null;
        try{
            lock.lock();
            while (lists.size()==0) {
                try {
                    consumer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            t = lists.removeFirst();
            System.out.println("get: "+ t);
            count --;
            producer.signalAll();
        }finally {
            lock.unlock();
        }
        return t;
    }

    private Integer getCount(){
        return count;
    }

    public static void main(String[] args) {
        MyContainer2 container1 = new MyContainer2();
        for(int j =0 ; j <2;j ++){
            Thread thread = new Thread(()->{
                for(int i =0; i< 25; i ++){
                    container1.put(Thread.currentThread().getName() + i);
                }
            });
            thread.start();
        }

        for(int j =0 ; j <10;j ++){
            Thread thread = new Thread(()->{
                for(int i =0; i< 5; i ++){
                    container1.get();
                }
            });
            thread.start();
        }
    }
}

CyclicBarrier

栅栏,满员发车,超过多少线程,才会释放锁

private void cyclicBarrier(){
        CyclicBarrier cyclicBarrier = new CyclicBarrier(20, new Runnable() {
            @Override
            public void run() {
                System.out.println("满人发车");
            }
        });

        for(int i = 0; i< 21; i++){
            Thread thread = new Thread(()->{
                try {
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
        }
    }

CyclicBarrier场景一:
复杂操作
1.数据库
2.网络
3.文件

Phaser:分阶段锁定

ReadWriteLock

共享锁: readLock
排他锁:writeLock

private void readWriteLock(){
        ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
        Lock readLock = readWriteLock.readLock();
        Lock writeLock = readWriteLock.writeLock();
    }
    private void read(Lock lock){
        try {
            lock.wait();
            System.out.println("read ...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    private void write(Lock lock){
        try {
            lock.wait();
            System.out.println("write ...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

Semaphore

作用:限流
实例: 车道、收费站、买票
信号量,允许多少个线程同时执行;有公平和非公平锁

  private void semaphore(){
        Semaphore semaphore = new Semaphore(1);//同时允许1个线程
        try {
            semaphore.acquire();// 获取一个许可,减1
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            semaphore.release(); //释放,加1
        }
        
    }

Exchanger

用于两个线程间交互数据
场景:以物易物;交换装备

    private void exchanger(){
        Exchanger exchanger = new Exchanger();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                String str = "s1";
                try {
                    str = (String) exchanger.exchange(str);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " str="+ str);
            }
        },"t1");

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                String str = "s2";
                try {
                    str=(String)exchanger.exchange(str);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " str="+ str);
            }
        },"t2");

        thread1.start();
        thread2.start();
    }

LockSupport

暂停一个线程,不用锁

LockSupport.park();//暂停线程
LockSupport.unpark();//取消暂停

   private void lockSupport(){
       Thread thread = new Thread(()->{
          for(int i=0; i< 10; i++){
              if(i == 5){
                  LockSupport.park();
              }
              System.out.println(i);
          }
       });
       thread.start();

        try {
            TimeUnit.SECONDS.sleep(8);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        LockSupport.unpark(thread);
        System.out.println("unpark the thread");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值