以下代码是单线程间通信示例
但是如果应用在多线程中会存在诸如一下问题
- LinkedList数据为空时,执行removeFirst方法
- LinkedList元素为10时,执行addLast方法 ```java import org.w3c.dom.events.Event; import sun.management.counter.perf.PerfInstrumentation;
import java.util.LinkedList; import java.util.concurrent.TimeUnit;
public class EventQueue { private final int max;
static class Event {
}
private final LinkedList<Event> eventQueue = 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 (eventQueue) {
if (eventQueue.size() >= max) {
console("the queue is full.");
try {
eventQueue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
console("the new event is submitted");
eventQueue.addLast(event);
eventQueue.notify();
}
}
public Event take() {
synchronized (eventQueue) {
if (eventQueue.isEmpty()) {
console("the queue is empty");
try {
eventQueue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Event event = eventQueue.removeFirst();
this.eventQueue.notify();
console("the event " + event + "is handle");
return event;
}
}
private void console(String message) {
System.out.printf("%s:%s\n", Thread.currentThread().getName(), message);
}
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.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "Consumer").start();
}
}
```
改进为多线程通信可用
改进点:
- 将if判断改为while
- 将notify更改为notifyAll即可