??? 概念:BlockQueue是Queue的子接口,BlockQueue中放入元素时,如果该队列满了,则线程被阻塞;当BlockQueue中取出元素时,如果该队列已空,则线程被阻塞。
class="java">/** * 消费者类 * @author Administrator * */ 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.take(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(getName() + "消费完成:" + bq); } } }
?
/** * 生产者类 * @author Administrator * */ 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 < 10; i++){ System.out.println(getName() + "生产者准备生产集合元素"); try { Thread.sleep(200); //尝试放入元素,如果已满,则堵塞 bq.put(strArr[i % 3]); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(getName() + "生产完成:" + bq); } } }
?
/** * 测试BlockingQueue * @author Administrator * */ public class BlockingQueueTest { public static void main(String[] args) { //设定BlockingQueue容量为1 BlockingQueue<String> bq = new ArrayBlockingQueue<String>(1); new Producer(bq).start(); //new Producer(bq).start(); //new Producer(bq).start(); new Consumer(bq).start(); } }
?