一个初始值为0的变量,两个线程对其交替操作,一个加1,一个减1,循环5次。
代码:
public class ProduceConsumer_BlockingQueue { public static void main(String[] args) { MyResource myResource = new MyResource(new ArrayBlockingQueue<String>(10)); new Thread(() -> { System.out.println(Thread.currentThread().getName() + "\t" + "生产线程开始了"); try { myResource.myProd(); } catch (InterruptedException e) { e.printStackTrace(); } }, "t1").start(); new Thread(() -> { System.out.println(Thread.currentThread().getName() + "\t" + "消费线程开始了"); System.out.println(); System.out.println(); try { myResource.myConsumer(); } catch (InterruptedException e) { e.printStackTrace(); } }, "t2").start(); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(); System.out.println(); System.out.println("5秒钟时间到了,大老板main线程叫停,活动结束"); myResource.stop(); } } class MyResource { private volatile boolean flag = true; private AtomicInteger atomicInteger = new AtomicInteger(); private BlockingQueue blockingQueue = null; public MyResource(BlockingQueue blockingQueue) { this.blockingQueue = blockingQueue; } public void myProd() throws InterruptedException { String data=null; boolean returnValue; while (flag) { data = atomicInteger.incrementAndGet()+""; returnValue = blockingQueue.offer(data + "", 2L, TimeUnit.SECONDS); if (returnValue) { System.out.println(Thread.currentThread().getName() + "\t 插入队列" + data + "成功"); } else { System.out.println(Thread.currentThread().getName() + "\t 插入队列" + data + "失败"); } TimeUnit.SECONDS.sleep(1); } System.out.println(Thread.currentThread().getName() + "\t 大老板叫停了,表示flage=false,生产动作结束"); } public void myConsumer() throws InterruptedException { String s =null; while (flag) { s = (String) blockingQueue.poll(2L, TimeUnit.SECONDS); if (null == s || s.equalsIgnoreCase("")) { flag = false; System.out.println(Thread.currentThread().getName() + "\t 超过2秒钟没有取到数据,消费退出"); return; } System.out.println(Thread.currentThread().getName() + "\t" + "消费队列" + s + "成功"); } System.out.println(Thread.currentThread().getName() + "\t 消费队列听了"); } public void stop() { flag = false; } }
结果:

posted on
浙公网安备 33010602011771号