-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadD.java
108 lines (97 loc) · 2.71 KB
/
ThreadD.java
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
public class ThreadD extends Thread {
private int time1 = 1;
private static boolean setting1 = false;
public synchronized int getTime1() {
while (setting1) {
try {
wait();
} catch (InterruptedException e) {
}
}
return time1;
}
public synchronized void setTime1(int t) {
this.time1 = t;
setting1 = false;
notifyAll();
}
public void run() {
number();
}
public void number() {
while (true) {
for (; getTime1() < 16; ) {
System.out.print(time1 + ", ");
setTime1(time1 + 1);
try {
sleep(750);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
class ThreadA extends Thread{
ThreadD timer1;
public ThreadA(ThreadD t){
this.timer1 = t;
}
public void run(){
synchronized(timer1){
while(true){
try {timer1.wait();} catch (InterruptedException e) {e.printStackTrace();}
if((timer1.getTime1() % 3 == 0) && (timer1.getTime1() % 5 != 0)){
System.out.print("fizz, ");
timer1.setTime1(timer1.getTime1()+1);
}
}
}
}
}
class ThreadB extends Thread{
ThreadD timer1;
public ThreadB(ThreadD t){
this.timer1 = t;
}
public void run(){
synchronized(timer1){
while(true){
try {timer1.wait();} catch (InterruptedException e) {e.printStackTrace();}
if(timer1.getTime1() % 5 == 0){
System.out.print("buzz, ");
timer1.setTime1(timer1.getTime1()+1);
}
}
}
}
}
class ThreadC extends Thread{
ThreadD timer1;
public ThreadC(ThreadD t){
this.timer1 = t;
}
public void run(){
synchronized(timer1){
while(true){
try {timer1.wait();} catch (InterruptedException e) {e.printStackTrace();}
if((timer1.getTime1() % 3 == 0) && (timer1.getTime1() % 5 == 0)){
System.out.print("fizzbuzz, ");
timer1.setTime1(timer1.getTime1()+1);
}
}
}
}
}
class BuzzerTester {
public static synchronized void main(String[] args) {
ThreadD timer1 = new ThreadD();
ThreadA t1 = new ThreadA(timer1);
ThreadB t2 = new ThreadB(timer1);
ThreadC t3 = new ThreadC(timer1);
timer1.start();
t1.start();
t2.start();
t3.start();
}
}