-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaFile1
More file actions
80 lines (62 loc) · 1.92 KB
/
JavaFile1
File metadata and controls
80 lines (62 loc) · 1.92 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.LinkedList;
import java.util.Queue;
import java.util.UUID;
public class Main {
private static Queue<String> synQueue = new LimitedQueue<>(2);
public static void main(String[] args) throws InterruptedException {
Producer producer = new Producer();
Consumer consumer = new Consumer();
producer.start();
consumer.start();
Thread.sleep(300);
producer.kill();
consumer.kill();
}
private static class Producer extends Thread {
private volatile boolean isRunning = true;
public void run() {
while (isRunning) {
String uuid = UUID.randomUUID().toString();
synchronized (synQueue) {
synQueue.add(uuid);
System.out.println("added " + uuid);
System.out.println("size is now " + synQueue.size());
}
}
}
void kill() {
isRunning = false;
}
}
private static class Consumer extends Thread {
private volatile boolean isRunning = true;
public void run() {
while (isRunning) {
if(synQueue.size()>0) {
synchronized (synQueue) {
String s = synQueue.poll();
System.out.println("got " + s);
System.out.println("size is now " + synQueue.size());
}
}
}
}
void kill() {
isRunning = false;
}
}
private static class LimitedQueue<E> extends LinkedList<E> {
private int limit;
LimitedQueue(int limit) {
this.limit = limit;
}
@Override
public boolean add(E o) {
if(super.size()<limit) {
super.add(o);
return true;
}
return false;
}
}
}