消费者与生产者
来源:互联网 发布: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(); }
阅读全文
0 0
- 生产者与消费者问题
- 生产者与消费者
- 生产者与消费者
- 生产者与消费者问题
- 消费者与生产者模式
- 消费者与生产者模式
- 消费者与生产者模式
- 生产者与消费者问题
- 生产者与消费者
- 生产者与消费者
- 生产者与消费者
- 生产者与消费者问题
- C# 生产者与消费者
- 生产者与消费者
- 生产者与消费者--一对一
- 死锁,生产者与消费者
- 生产者与消费者模型
- java 生产者与消费者
- BM算法
- XListView使用
- 使用jQuery中prependTo appendTo图片轮播凸出效果
- MindManager 2018如何新建维恩图
- 你知道Guitar Pro 7可以编辑中文歌词吗?
- 消费者与生产者
- hibernate.hbm2ddl.auto四种取值
- java求0—7所能组成的奇数个数。
- JAVA多线程实现的四种方式
- Linux命令使用积累
- 201710201400memo
- easyui datagrid 可编辑类型单元格-适当调整高度
- c++构造器中成员函数初始化
- maven pom.xml配置详解