生产者
1 import java.util.Random; 2 3 4 public class Producer extends Thread { 5 6 private Storage<Product> storage; 7 8 public Producer(Storage<Product> storage) { 9 this.storage = storage; 10 } 11 12 @Override 13 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 Storage<Product> storage; 4 5 public Consumer(Storage<Product> storage) { 6 this.storage = storage; 7 } 8 9 @Override 10 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 @Override 16 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 * @param <E> 10 */ 11 public class Storage<E> { 12 13 private List<E> list = new ArrayList<E>(); 14 15 /** 16 * 入仓 17 * 18 * @param e 19 */ 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 e 45 */ 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 * @return 73 */ 74 public boolean isEmpty() { 75 return list.isEmpty(); 76 } 77 78 /** 79 * 判断当前仓库是否已满 80 * 81 * @return 82 */ 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 Storage<Product> storage = new Storage<Product>(); 6 7 new Producer(storage).start(); 8 new Consumer(storage).start(); 9 } 10 11 }
时间: 2024-10-12 21:32:26