9 线程通信之生产者于消费者终极版

传统版

public class ProdConsumer_BlockQueueDemo {

    private volatile int num;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment(){
       lock.lock();
       try{
          // 不能用if 
           while (num != 0){
               // 等待不能生产
               condition.await();
           }
           num++;
           System.out.println(Thread.currentThread().getName()+" "+num);
           condition.signalAll();
       }catch (Exception ignored){
       }finally {
           lock.unlock();
       }
    }

    public void decrement(){
        lock.lock();
        try{
          // 不能用if
            while (num == 0){
                // 等待不能消费
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+" "+num);
            condition.signalAll();
        }catch (Exception ignored){
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ProdConsumer_BlockQueueDemo prodConsumer_blockQueueDemo = new ProdConsumer_BlockQueueDemo();

            new Thread(()->{
                for (int i = 0; i < 5; i++) {
                    prodConsumer_blockQueueDemo.increment();
                }
            },"AAA").start();
            new Thread(()->{
                for (int i = 0; i < 5; i++) {
                    prodConsumer_blockQueueDemo.decrement();
                }
            },"BBB").start();

            new Thread(()->{
                for (int i = 0; i < 5; i++) {
                    prodConsumer_blockQueueDemo.increment();
                }
            },"CCC").start();
            new Thread(()->{
                for (int i = 0; i < 5; i++) {
                    prodConsumer_blockQueueDemo.decrement();
                }
            },"DDD").start();


    }
}

终极版

class MyResource{

    public volatile boolean flag = true;
    private final AtomicInteger atomicInteger = new AtomicInteger();
    private final BlockingQueue<String> blockingQueue;

    public MyResource(BlockingQueue<String>  blockingQueue){
        this.blockingQueue = blockingQueue;
    }

    public void myProd() throws InterruptedException {
        String data;
        while (flag){
            data =  atomicInteger.incrementAndGet()+"";
            if (blockingQueue.offer(data, 2L, TimeUnit.SECONDS)){
                System.out.println(Thread.currentThread().getName()+" 插入队列成功");
            }else{
                System.out.println(Thread.currentThread().getName()+" 插入队列失败");
            }
            TimeUnit.SECONDS.sleep(1);
        }
    }

    public void myConsumer() throws InterruptedException {
        String result;
        while (flag){
            result = blockingQueue.poll(2L, TimeUnit.SECONDS);
            if (null == result || "".equals(result)){
                flag = false;
                System.out.println(Thread.currentThread().getName()+ "消费失败");
                return;
            }
            System.out.println(Thread.currentThread().getName()+" 消费成功:"+result);
        }
    }
}

public class BlockingQueueDemo {

    public static void main(String[] args) throws InterruptedException {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<>(3));
        while (myResource.flag){
            new Thread(()->{
                try {
                    myResource.myProd();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"AA").start();

            new Thread(()->{
                try {
                    myResource.myConsumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
               }
            },"BB").start();

            TimeUnit.SECONDS.sleep(5);
            System.out.println("时间到停止。。。。。");
            myResource.flag = false;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值