线程通讯--BlockingQueue
Producer线程
package com.thread.communication.blockingqueue; import java.util.concurrent.BlockingQueue; public class Producer extends Thread{ private BlockingQueue<String> bq; public Producer(BlockingQueue<String> bq){ this.bq=bq; } public void run(){ String[] strArr = new String[] {"Java","Struts","Spring"}; for(int i=0;i<99999999;i++){ System.out.println(getName() + "生产者准备生产集合元素"); try{ Thread.sleep(200); //如果传入的的bq的length是1,那么put一个值,就会出现阻塞现象 bq.put(strArr[i % 3]);//求余数 0 1 2 }catch(Exception ex){ ex.printStackTrace(); } System.out.println(getName()+"生产完成"+ bq); } } }
Consumer线程
package com.thread.communication.blockingqueue; import java.util.concurrent.BlockingQueue; public class Consumer extends Thread{ private BlockingQueue<String> bq; public Consumer(BlockingQueue<String> bq){ this.bq=bq; } public void run(){ while(true){ System.out.println(getName()+"消费者准备消费集合元素"); try{ Thread.sleep(200); //当bq被取空时,出现阻塞 bq.take(); }catch(Exception ex){ ex.printStackTrace(); } System.out.println(getName()+ "消费完成"+bq); } } }
测试类
package com.thread.communication.blockingqueue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class BlockingQueueTest { public static void main(String[] args){ BlockingQueue<String> bq = new ArrayBlockingQueue<>(1); new Producer(bq).start(); new Producer(bq).start(); new Producer(bq).start(); new Consumer(bq).start(); } }
本文来自博客园,作者:月色深潭,交流群:733423266,转载请注明原文链接:https://www.cnblogs.com/moonpool/p/5503287.html