队列:先进先出的数据结构(FIFO)
java中的队列接口在java.util包下
常见的对列实现类有LinkedList
常见的阻塞队列:LinkedBlockingDeque,可以设置固定的容量,当队列有数据的时候会通知消费者消费,当对应满的时候会让生产者等待。
用LinkedBlockingDeque实现生产者消费者模式:两个厨师做烧饼,两个顾客买烧饼
@Test public void test15() { final int count = 5; LinkedBlockingDeque<String> shaobingQueue = new LinkedBlockingDeque<>(3); // List<String> xiaoBaiMsg = new LinkedList<>(); List<String> chushi1Msg = new LinkedList<>(); List<String> chushi2Msg = new LinkedList<>(); List<String> roadPeopleAmsg = new LinkedList<>(); List<String> roadPeopleBmsg = new LinkedList<>(); Thread roadPeopleA = new Thread(() -> { for (int i = 0; i < count; i++) { String take = null; try { take = shaobingQueue.take();//队列没数据的时候会通知线程等待 } catch (InterruptedException e) { e.printStackTrace(); } roadPeopleAmsg.add(String.format("%d 路人甲买到了 [%s]", System.currentTimeMillis(), take)); } }); Thread roadPeopleB = new Thread(() -> { for (int i = 0; i < count; i++) { String take = null; try { take = shaobingQueue.take(); } catch (InterruptedException e) { e.printStackTrace(); } roadPeopleBmsg.add(String.format("%d 路人乙买到了 [%s]", System.currentTimeMillis(), take)); } }); Thread chushi1 = new Thread(() -> { for (int i = 0; i < count; i++) { String format = String.format("第%d个烧饼", i + 1); try { shaobingQueue.put(format);//当队列满的时候会让线程等待 } catch (InterruptedException e) { e.printStackTrace(); } chushi1Msg.add(String.format("%d chushi1制作了 [%s],当前烧饼数量:%d", System.currentTimeMillis(), format, shaobingQueue.size())); } }); Thread chushi2 = new Thread(() -> { for (int i = 0; i < count; i++) { String format = String.format("第%d个烧饼", i + 1); try { shaobingQueue.put(format); } catch (InterruptedException e) { e.printStackTrace(); } chushi2Msg.add(String.format("%d chushi2制作了 [%s],当前烧饼数量:%d", System.currentTimeMillis(), format, shaobingQueue.size())); } }); chushi1.start(); chushi2.start(); roadPeopleA.start(); roadPeopleB.start(); try { chushi1.join(); chushi2.join(); roadPeopleA.join(); roadPeopleB.join(); } catch (InterruptedException e) { SmallTool.printTimeAndThread("join 产生中断 "+ e.getMessage()); } System.out.println(chushi1Msg.stream().collect(Collectors.joining("\n"))); System.out.println(chushi2Msg.stream().collect(Collectors.joining("\n"))); System.out.println("--------"); System.out.println(roadPeopleAmsg.stream().collect(Collectors.joining("\n"))); System.out.println(roadPeopleBmsg.stream().collect(Collectors.joining("\n"))); }
标签:String,Thread,format,队列,基础,阻塞,System,take,new From: https://www.cnblogs.com/wscw/p/17249881.html