package com.dnaer.core.sale.saleinvitelog.util; import ch.qos.logback.core.util.TimeUtil; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; class Producer { public static volatile Boolean TAG = false; private AtomicInteger atomicInteger =new AtomicInteger(0); private BlockingQueue<Integer> blockingQueue; public Producer (BlockingQueue<Integer> blockingQueue) { this.blockingQueue = blockingQueue; } public void pro(){ while (TAG) { try { int value = atomicInteger.incrementAndGet(); blockingQueue.offer(value,2,TimeUnit.SECONDS); System.out.println("生产者:t1"+" , 生产数据"+value); TimeUnit.MILLISECONDS.sleep(100); }catch (Exception e) { e.printStackTrace(); } } } public void cons() { while (TAG) { try { Integer value =(Integer) blockingQueue.poll(2,TimeUnit.SECONDS); if (value == null) { TAG = false; System.out.println("\t\t消费者,t2"+"取消监听"); }else { System.out.println("\t\t消费者,t2"+"获取数据:"+value); } }catch (Exception e) { e.printStackTrace(); } } } } public class ProAndConsumerThreadTest { public static void main(String[] args) throws Exception{ TimeUnit.SECONDS.sleep(1); try { ArrayBlockingQueue<Integer> arrayBlockingQueue =new ArrayBlockingQueue<>(3); Producer.TAG =true; Producer producer = new Producer(arrayBlockingQueue); new Thread(() ->{ producer.pro(); }).start(); new Thread(() ->{ producer.cons(); }).start(); }catch (Exception e) { e.printStackTrace(); } TimeUnit.SECONDS.sleep(3); Producer.TAG = false; } }
使用BlockQueue,模仿写一个生成者和消费者demo
最新推荐文章于 2021-03-22 00:17:34 发布