-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventQueue.java
More file actions
60 lines (52 loc) · 1.54 KB
/
EventQueue.java
File metadata and controls
60 lines (52 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package chapter05;
import java.util.LinkedList;
/**
* Created by zhangzhao on 2018/8/23.
*/
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){
while(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.notifyAll();
}
}
public Event take(){
synchronized (eventQueue){
while(eventQueue.isEmpty()){
console("the queue is empty");
try {
eventQueue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Event event = eventQueue.removeFirst();
this.eventQueue.notifyAll();
console("the event +" + event + "is handled");
return event;
}
}
private void console(String message){
System.out.printf("%s:%s\n",Thread.currentThread().getName(),message);
}
}