生產者在倉庫沒有滿的時候進行生產,滿了後等待dom
消費者在倉庫有存貨事新型消費,沒貨是等待ide
#Phonethis
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; } }
#Storagespa
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保證對象只能被一個線程佔用code
執行wat()後,當前線程處於等待狀態,釋放鎖,讓別的線程能夠繼續執行對象
執行notify()後,喚醒其餘處於wait()狀態的線程繼續執行blog
#Producerget
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); } }
#Consumerit
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(); } } }