阻塞队列实现生产者-消费者

package com.demo.blockingqueue;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyData //资源类
{
    private volatile boolean FLAG=true;
    private AtomicInteger atomicInteger=new AtomicInteger();

    BlockingQueue<String> blockingQueue=null;

    public MyData(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(Thread.currentThread().getName());
    }



    public void product() throws Exception{
        String data = null;
        Boolean resultValue;
        while (FLAG){
            data=atomicInteger.incrementAndGet()+"";
            resultValue = blockingQueue.offer(data + "", 2L, TimeUnit.SECONDS);
            if(resultValue){
                System.out.println(Thread.currentThread().getName()+"----插入队列"+data+"成功");
            }else {
                System.out.println(Thread.currentThread().getName()+"插入队列"+data+"失败");
            }
            TimeUnit.MILLISECONDS.sleep(100);
        }

        System.out.println(Thread.currentThread().getName()+"大老板叫停了,表示FLAG=false 生产动作结束");

    }

    public void consumer() throws Exception{
        String result = null;
        while (FLAG){
            result=blockingQueue.poll(2L,TimeUnit.SECONDS);
            if(result==null||result.equalsIgnoreCase("")){
                FLAG=false;
                System.out.println(Thread.currentThread().getName()+"超过2秒没有拿到蛋糕消费者退出");
                System.out.println();
                System.out.println();
                return;
            }
            System.out.println(Thread.currentThread().getName()+"*******消费队列"+result+"成功");
        }
    }
    public void stop(){
        this.FLAG=false;
    }

}


public class ProducterAndConsumer {

    public static void main(String[] args) {
        MyData myData=new MyData(new ArrayBlockingQueue<String>(10));

        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"生产线程启动");
            try {
                myData.product();
            } catch (Exception e) {
                e.printStackTrace();
            }

        },"product").start();


        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"消费者线程启动");

            try {
                myData.consumer();
            } catch (Exception e) {
                e.printStackTrace();
            }

        },"consumer").start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println();
        System.out.println();
        System.out.println("5秒钟到,大老板main线程 叫停");
        myData.stop();
    }
}

 

posted @ 2020-02-29 22:38  valar-dohaeris  阅读(160)  评论(0编辑  收藏  举报