用 wait-notify 写一段代码来解决生产者-消费者问题?
public class EventStorage { private int maxSize; private List<Date> storage; public EventStorage(){ maxSize = 10; storage = new LinkedList<Date>(); } public synchronized void set(){ while(storage.size() == maxSize){ try{ wait(); }catch(InterruptedException e){ e.printStackTrace(); } } storage.add(new Date()); System.out.printf("Set:%d",storage.size()); notifyAll(); } public synchronized void get(){ while(storage.size() == 0){ try{ wait(); }catch(InterrupteException e){ e.printStackTrace(); } } System.out.printf("Get:%d:%s",storage.size(),((LinkedList<?>storage).poll()); notifyAll(); }
public class Producer implements Runnable{ private EventStorage storge; public Producer(EventStorage storge;){ this.storage = storage; } public void run(){ for(int i = 0;i< 100; i++){ storage.set(); } } }
public class Consumer implements Runnable{ private EventStorage storage; public Consumer(EventStorage storage) { this.storage = storage; } public void run(){ for(int i=0;i<100;i++){ storage.get(); } } }