事件存储器(临界资源)
package producer_consumer;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
public class EventStorage {
private int maxSize;
private Queue<Date> storage;
public EventStorage() {
maxSize = 10;
storage = new LinkedList<>();
}
public synchronized void set(){
while (storage.size()==maxSize){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storage.offer(new Date());
System.out.printf("Set:%d ",storage.size());
notify();
}
public synchronized void get(){
while (storage.size()==0){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String element=storage.poll().toString();
System.out.printf("Get: %d: %s\n",storage.size(),element);
notify();
}
}
生产者
package producer_consumer;
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 producer_consumer;
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();
}
}
}
Main测试类
package producer_consumer
public class Main {
public static void main(String[] args) {
EventStorage storage=new EventStorage()
Thread thread1=new Thread(new Producer(storage))
Thread thread2=new Thread(new Consumer(storage))
thread2.start()
thread1.start()
}
}