生产消费_lock和阻塞队列

lock

  1. 这里的lock只需要一把锁
    因为同时还要配合状态 一起决定
  2. 一定要在try里面用 一定要unlock
public class Test {
    public static void main(String[] args) {
        //传统版本
        AirConditional airConditional = new AirConditional();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                airConditional.produce();
            }
        }).start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                airConditional.consume();
            }
        }).start();
    }
}
class AirConditional{
    int temp ;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void produce(){
        try {
            lock.lock();
            while( temp != 0){
                condition.await();
            }
            temp++;
            System.out.println("生产后为"+temp);
            condition.signalAll();
        }catch (Exception e){

        }
        finally {
             lock.unlock();   
        }
    }
    public void consume(){
        try {
            lock.lock();
            while( temp != 1){
                condition.await();
            }
            temp--;
            System.out.println("消费后为"+temp);
            condition.signalAll();
        }catch (Exception e){

        }
        finally {
            lock.unlock();
        }
    }
}

bq

但如果不睡的话,会稀巴烂
本质就是put和take,加定时的话就是offer和poll

class AirConditional_bq{
    public volatile boolean flag = true;
    private AtomicInteger integer = new AtomicInteger();
    //为什么要string 就是因为解耦-原子类
    private BlockingQueue<String> bq;

    public AirConditional_bq(BlockingQueue<String> bq) {
        this.bq = bq;
    }

    public void add(){
        while(flag){
            int i = integer.incrementAndGet();
            try {Thread.sleep(1000);
                bq.put(i+"");
                System.out.println("生产了"+i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void minus(){
        while(flag){
            try {Thread.sleep(1000);
                String take = bq.take();
                System.out.println("消费了"+take);
                integer.decrementAndGet();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        AirConditional_bq conditionalBq = new AirConditional_bq(new ArrayBlockingQueue<>(1));
        new Thread(()->{
            conditionalBq.add();
        }).start();
        new Thread(()->{
            conditionalBq.minus();
        }).start();
        Thread.sleep(2000);
        conditionalBq.flag = false;
        System.out.println("主线程退出");
    }
}
posted @ 2021-09-10 10:55  常熟阿诺  阅读(55)  评论(2编辑  收藏  举报