消费者与生产者

来源:互联网 发布:python spawn 编辑:程序博客网 时间:2024/06/06 10:00

生产者:

public class Provider1 implements Runnable{    private BlockingQueue<String> queue;    private static AtomicInteger count=new AtomicInteger();    private volatile boolean isRunning=true;//volatile修饰,多线程访问变量值改变不会被忽略    private static final int MILLIS=1000;    @SuppressWarnings({ "rawtypes", "unchecked" })    public  Provider1(BlockingQueue queue) {        this.queue=queue;    }    @Override    public void run() {        System.out.println("生产者线程开启");        Random r=new  Random();        try {            while(isRunning){                Thread.sleep(r.nextInt(MILLIS));//0~MILLIS之间的伪随机数                String data="data:"+count.getAndIncrement();                System.out.println(Thread.currentThread().getName()+"将数据:"+data+"放入队列。。");                //                if(!queue.offer(data)){//offer:数据插入失败,数据丢失//                    System.out.println("生产者放入队列数据失败--"+data);//                }                queue.put(data);//put:将指定元素插入此队列中,将等待可用的空间(如果有必要)。             }        } catch (Exception e) {            e.printStackTrace();            Thread.currentThread().interrupt();        }finally {            System.out.println("生产者线程关闭。。");        }    }    public void stop(){        isRunning=false;        System.out.println("生产者stop!"+count);    }}

消费者:

public class Consumer1 implements Runnable{    private BlockingQueue<String> queue;    private boolean isRunning=true;    private static final int MILLIS=1000;    public Consumer1(BlockingQueue<String> queue) {        this.queue=queue;    }    @Override    public void run() {        System.out.println("消费者线程开启。。");        Random r=new Random();            try {                while (isRunning) {                   String data=queue.take();//获取并移除此队列的头部,在元素变得可用之前一直等待(如果有必要)。                    System.out.println("正在取数据:"+data);                    if(null==data){                        isRunning=false;                    }else{                        System.out.println(Thread.currentThread().getName()+"从队列取出数据:" + data + ",消费");                        Thread.sleep(r.nextInt(MILLIS));                    }                }            } catch (InterruptedException e) {                e.printStackTrace();                Thread.currentThread().interrupt();            }finally {                System.out.println("消费者线程关闭。。。");            }    }}

测试:

public static void main(String[] args) throws InterruptedException {        BlockingQueue<String> queue = new LinkedBlockingDeque<>(2);        Provider1 p1 = new Provider1(queue);        Consumer1 c1 = new Consumer1(queue);        ExecutorService service = Executors.newCachedThreadPool();        service.execute(c1);        service.execute(p1);        service.execute(p1);        service.execute(p1);        service.execute(p1);        Thread.sleep(2000);        p1.stop();        service.shutdown();        //        service.shutdownNow();    }