-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomNumberMulti.java
More file actions
89 lines (78 loc) · 2.26 KB
/
RandomNumberMulti.java
File metadata and controls
89 lines (78 loc) · 2.26 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
import java.util.Random;
class NumberGenerator extends Thread{
private final NumberProcessor processor;
public NumberGenerator(NumberProcessor processor){
this.processor = processor;
}
@Override
public void run(){
Random random = new Random();
int count = 0;
while (count<10) {
int number = random.nextInt(100);
System.out.println("Generated: " + number);
processor.processNumber(number);
count++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
processor.setDone();
}
}
class NumberProcessor{
private int number;
private boolean done = false;
public synchronized void processNumber(int number){
this.number = number;
notifyAll();
}
public synchronized void setDone(){
done = true;
notifyAll();
}
public void square(){
while (true) {
synchronized (this) {
try {
wait();
if (done) break;
if (number%2 == 0) {
System.out.println("Square: " + (number*number));
}
}
catch (InterruptedException e) {
break;
}
}
}
}
public void cube(){
while (true) {
synchronized (this) {
try {
wait();
if (done) break;
if (number%2 != 0) {
System.out.println("Cube: " + (number*number*number));
}
} catch (InterruptedException e) {
break;
}
}
}
}
}
public class RandomNumberMulti {
public static void main(String[] args) {
NumberProcessor processor = new NumberProcessor();
NumberGenerator generator = new NumberGenerator(processor);
Thread squareThread = new Thread(processor::square);
Thread cubeThread = new Thread(processor::cube);
generator.start();
squareThread.start();
cubeThread.start();
}
}