原理
生产者在仓库没有满的时候进行生产,满了后等待
消费者在仓库有存货事新型消费,没货是等待
示例
#Phone
public class Phone { private int id; public Phone() { id = new Random().nextInt(); } public int getId() { return id; } public void setId(int id) { this.id = id; } }
#Storage
public class Storage { int index; private final int MAX; Queue<Phone> phoneQueue; public Storage(int max) { index = 0; MAX = max; phoneQueue = new ArrayDeque<>(MAX); } public synchronized Phone consume() { while (index <= 0) { try { System.out.println("仓库空了,等待中。。。。。"); wait(); System.out.println("仓库不空了,继续消费。。。。。"); }catch (InterruptedException e) { e.printStackTrace(); } } Phone phone = phoneQueue.poll(); System.out.println("consume Phone:" + phone.getId()); index--; notify(); return phone; } public synchronized void produce(Phone phone) { while (index >= MAX) { try { System.out.println("仓库满了,等待中。。。"); wait(); System.out.println("仓库不满了,继续生产。。。"); }catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("produce Phone:" + phone.getId()); index++; phoneQueue.add(phone); notify(); } }
说明:
synchonized保证对象只能被一个线程占用
执行wat()后,当前线程处于等待状态,释放锁,让别的线程可以继续执行
执行notify()后,唤醒其他处于wait()状态的线程继续执行
#Producer
public class Producer implements Runnable{ Storage storage; public Producer(Storage storage) { this.storage = storage; } @Override public void run() { Phone phone = new Phone(); storage.produce(phone); } }
#Consumer
public class Consumer implements Runnable{ Storage storage; public Consumer(Storage storage) { this.storage = storage; } @Override public void run() { try { Thread.sleep(5000); }catch (InterruptedException e) { e.printStackTrace(); } Phone phone = storage.consume(); } }
#Main
public class Main { public static void main(String[] args) { Storage storage = new Storage(35); for (int i = 0; i < 40; i++) { new Thread(new Producer(storage)).start(); } for (int i = 0; i < 40; i++) { new Thread(new Consumer(storage)).start(); } } }