package com.wjxie.linked.blocking.queue; public class Producer extends Thread { public Producer(String name) { super(name); } @Override public void run() { while (true) { System.out.println("Producer queue size: " + Main.queue.size()); try { Item item = new Item(); Main.queue.put(item); System.out.println(this.getName() + " produce " + item); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.wjxie.linked.blocking.queue; public class Consumer extends Thread { public Consumer(String name) { super(name); } @Override public void run() { while (true) { System.out.println("Consumer queue size: " + Main.queue.size()); try { Item item = Main.queue.take(); System.out.println(this.getName() + " consume " + item); Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.wjxie.linked.blocking.queue; import java.util.concurrent.LinkedBlockingQueue; public class Main { public static LinkedBlockingQueue<Item> queue = new LinkedBlockingQueue<Item>(100); public static void main(String[] args) { Thread p = new Producer("[P]"); Thread p2 = new Producer("[P2]"); Thread c = new Consumer("[C]"); Thread c2 = new Consumer("[C2]"); p.start(); p2.start(); c.start(); c2.start(); } }
package com.wjxie.linked.blocking.queue; public class Item { private int id; public Item() { id = ID.getID(); } @Override public String toString() { return "Item[" + id + "]"; } static class ID { private static int id = 0; public static int getID() { return ++id; } } }