-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProdCons.java
More file actions
112 lines (97 loc) · 2.3 KB
/
ProdCons.java
File metadata and controls
112 lines (97 loc) · 2.3 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* Solves consumer - producer problem.
*/
package threads;
import java.util.ArrayList;
import java.util.Random;
/**
* Buffer class with an ArrayList of values.
*/
class Buffer {
public static ArrayList<Integer> value = new ArrayList<Integer>();
}
/**
* Abscrtact class for common methods.
*/
abstract class MyThread {
// Rondomised seed to produce random values.
public static Random rnd = new Random();
/**
* Puts the thread to sleep for up to 5 seconds
* and handles exceptions.
*/
public void trySleepRnd() {
try {
Thread.sleep(rnd.nextInt(5000));
} catch(InterruptedException e) {};
}
/**
* Sets the state of thread to wait for the object
* and handles exceptions.
* @param obj The object to wait for.
*/
public void tryWait(Object obj) {
try {
obj.wait();
} catch(InterruptedException e) {};
}
}
/**
* Producer thread class.
*/
class Producer extends MyThread implements Runnable {
/**
* Tries to produce a value to the buffer, if
* buffer is full - waits.
*/
public void run() {
while(true) {
synchronized(Buffer.value) {
if (Buffer.value.size() < 3) {
Buffer.value.add(rnd.nextInt(100));
System.out.println("Value produced: " + Buffer.value);
Buffer.value.notifyAll();
} else {
tryWait(Buffer.value);
}
}
trySleepRnd(); // to make it more fun
}
}
}
/**
* Consumer thread class.
*/
class Consumer extends MyThread implements Runnable {
/**
* Tries to consume a value from the buffer, if
* buffer is empty - waits.
*/
public void run() {
while(true) {
synchronized(Buffer.value) {
if (Buffer.value.size() > 0) {
int top = Buffer.value.remove(0);
System.out.println("Value consumed " + top);
Buffer.value.notifyAll();
} else {
tryWait(Buffer.value);
}
}
trySleepRnd(); // to make it more fun
}
}
}
class ProdCons {
/**
* Spawns two threads and starts them.
* @param args Program arguments, not used.
*/
public static void main(String[] args) {
System.out.println(Buffer.value);
Thread prod = new Thread(new Producer(), "Producer");
Thread cons = new Thread(new Consumer(), "Consumer");
prod.start();
cons.start();
}
}