1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| public class TestProductor { public static void main(String[] args) { Storage storage = new Storage();
new Thread(new Producer(storage),"p1").start(); new Thread(new Consumer(storage),"c1").start(); }
}
class Producer implements Runnable{ private Storage storage; public Producer(){
}
public Producer(Storage storage){ this.storage = storage; }
@Override public void run() { for (int i = 0; i < 100; i++) { try { Thread.sleep(100); storage.put(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
class Consumer implements Runnable{
private Storage storage;
public Consumer(Storage storage){ this.storage = storage; } public Consumer(){ }
@Override public void run() { for (int i = 0; i < 100; i++) { try { Thread.sleep(100); storage.pop(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
class Storage{ private final int MAX_SIZE = 10; private LinkedList<Object> list = new LinkedList<>();
public void put() { synchronized (list) { while (list.size()+1 > MAX_SIZE) { System.out.println("【生产者" + Thread.currentThread().getName() + "】仓库已满,"); try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.add(new Object()); System.out.println("【生产者" + Thread.currentThread().getName() + "】生产一个产品,现库存" + list.size()); list.notifyAll(); } }
public void pop() { synchronized (list) { while (list.size() == 0) { System.out.println("【消费者" + Thread.currentThread().getName() + "】仓库为空,消费了0个产品"); try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.remove(); System.out.println("【消费者" + Thread.currentThread().getName() + "】消费一个产品,现库存:" + list.size()); list.notifyAll(); } } }
|