本文是学习网络上的文章时的总结,感谢大家无私的分享。
其实很简单,大家看代码就知道是神马意思了。
package chapter2; import java.util.Date; import java.util.LinkedList; import java.util.List; 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(); } } ((LinkedList<Date>) storage).offer(new Date()); System.out.println("Set:"+storage.size()); notifyAll(); } public synchronized void get(){ while(storage.size()==0){ System.out.println("---------------------------等待中--------------------"); try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.printf("Get:%d:%s",storage.size(),((LinkedList<Date>) storage).poll()); notifyAll(); } }
package chapter2; public class Producer implements Runnable{ private EventStorage storage; public Producer(EventStorage storage){ this.storage = storage; } @Override public void run() { for(int i=0;i<100;i++){ storage.set(); } } }
package chapter2; public class Consumer implements Runnable { private EventStorage storage; public Consumer(EventStorage storage){ this.storage = storage; } @Override public void run() { for(int i=0;i<100;i++){ storage.get(); } } }
这是对生产者和消费者问题的一种简单解决。
时间: 2024-11-05 11:27:30