生产者
1 import java.util.Random; 2 3 4 public class Producer extends Thread { 5 6 private Storagestorage; 7 8 public Producer(Storage storage) { 9 this.storage = storage;10 }11 12 @Override13 public void run() {14 produce();15 }16 17 private void produce() {18 while (true) {19 Product product = new Product(new Random().nextInt(100));20 storage.enStorage(product);21 }22 }23 24 25 }
消费者
1 public class Consumer extends Thread { 2 3 private Storagestorage; 4 5 public Consumer(Storage storage) { 6 this.storage = storage; 7 } 8 9 @Override10 public void run() {11 consume();12 }13 14 private void consume() {15 while (true) {16 storage.deStorage();17 }18 }19 20 21 }
产品
1 /** 2 * 产品 3 * 4 * @author thief 5 * 6 */ 7 public class Product { 8 9 private int id;10 11 public Product(int id) {12 this.id = id;13 }14 15 @Override16 public String toString() {17 return "产品:" + id;18 }19 20 }
仓库
1 import java.util.ArrayList; 2 import java.util.List; 3 4 /** 5 * 仓库 6 * 7 * @author Thief 8 * 9 * @param10 */11 public class Storage {12 13 private List list = new ArrayList ();14 15 /**16 * 入仓17 * 18 * @param e19 */20 public void enStorage(E e) {21 synchronized (list) {22 while (this.isFull()) {23 try {24 System.out.println("仓库已满");25 list.wait();26 } catch (InterruptedException e1) {27 e1.printStackTrace();28 }29 }30 list.add(e);31 System.out.println(Thread.currentThread().getName() + "生产产品");32 try {33 Thread.sleep(10);34 } catch (InterruptedException e1) {35 e1.printStackTrace();36 }37 list.notifyAll();38 }39 }40 41 /**42 * 出仓43 * 44 * @param e45 */46 public E deStorage() {47 synchronized (list) {48 while(this.isEmpty()) {49 try {50 System.out.println("仓库已空");51 list.wait();52 } catch (InterruptedException e1) {53 e1.printStackTrace();54 }55 }56 E e = list.get(0);57 list.remove(0);58 System.out.println(Thread.currentThread().getName() + "消费产品");59 try {60 Thread.sleep(1000);61 } catch (InterruptedException e1) {62 e1.printStackTrace();63 }64 list.notifyAll();65 return e;66 }67 }68 69 /**70 * 判断当前仓库是否为空71 * 72 * @return73 */74 public boolean isEmpty() {75 return list.isEmpty();76 }77 78 /**79 * 判断当前仓库是否已满80 * 81 * @return82 */83 public boolean isFull() {84 return list.size() == 5;85 }86 87 }
测试代码
1 public class Test { 2 3 public static void main(String[] args) { 4 5 Storagestorage = new Storage (); 6 7 new Producer(storage).start(); 8 new Consumer(storage).start(); 9 }10 11 }