package concurrent;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
public class EventQueue {
private final int max;
static class Event {
}
private final LinkedList<Event> evnetQueue = new LinkedList<>();
private final static int DEFAULT_MAX_EVENT = 10;
public EventQueue() {
this(DEFAULT_MAX_EVENT);
}
public EventQueue(int max) {
this.max = max;
}
public void offer(Event event) {
synchronized (evnetQueue) {
if (evnetQueue.size() >= max) {
try {
System.out.println(" the queue is full");
evnetQueue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(" the new event is submitted");
evnetQueue.addLast(event);
evnetQueue.notify();
}
}
public Event take() {
synchronized (evnetQueue) {
if (evnetQueue.isEmpty()) {
try {
System.out.println("the queue is empty");
evnetQueue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Event event = evnetQueue.removeFirst();
this.evnetQueue.notify();
System.out.println("the event" + event + " is handled");
return event;
}
}
public static void main(String[] args) {
final EventQueue eventQueue = new EventQueue();
new Thread(() -> {
for (; ; ) {
eventQueue.offer(new EventQueue.Event());
}
}, "Producer").start();
new Thread(() -> {
for (; ; ) {
eventQueue.take();
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "Consumer").start();
}
}
the new event is submitted
the new event is submitted
the new event is submitted
the new event is submitted
the eventconcurrent.EventQueue$Event@346827f is handled
the new event is submitted
the new event is submitted
the new event is submitted
the new event is submitted
the new event is submitted
the new event is submitted
the new event is submitted
the queue is full
the eventconcurrent.EventQueue$Event@d817c67 is handled
the new event is submitted
the queue is full
the eventconcurrent.EventQueue$Event@9bee90f is handled
the new event is submitted
the queue is full
the eventconcurrent.EventQueue$Event@4cbc765c is handled
该例主要用到了 wait 和 notify,使用它们的注意事项如下。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/chengqiuming/article/details/123363431
内容来源于网络,如有侵权,请联系作者删除!