-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1195.fizz-buzz-multithreaded.java
63 lines (54 loc) · 1.92 KB
/
1195.fizz-buzz-multithreaded.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
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.IntConsumer;
public class FizzBuzz {
private int n;
private int current = 1;
private ReentrantLock lock = new ReentrantLock(true);
public FizzBuzz(int n) {
this.n = n;
}
// printFizz.run() outputs "fizz".
public void fizz(Runnable printFizz) throws InterruptedException {
do {
this.lock.lock();
if (this.current <= this.n && this.current % 3 == 0 && this.current % 5 != 0) {
printFizz.run();
this.current++;
}
this.lock.unlock();
} while (this.current <= this.n);
}
// printBuzz.run() outputs "buzz".
public void buzz(Runnable printBuzz) throws InterruptedException {
do {
this.lock.lock();
if (this.current <= this.n && this.current % 3 != 0 && this.current % 5 == 0) {
printBuzz.run();
this.current++;
}
this.lock.unlock();
} while (this.current <= this.n);
}
// printFizzBuzz.run() outputs "fizzbuzz".
public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
do {
this.lock.lock();
if (this.current <= this.n && this.current % 3 == 0 && this.current % 5 == 0) {
printFizzBuzz.run();
this.current++;
}
this.lock.unlock();
} while (this.current <= this.n);
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void number(IntConsumer printNumber) throws InterruptedException {
do {
this.lock.lock();
if (this.current <= this.n && this.current % 3 != 0 && this.current % 5 != 0) {
printNumber.accept(this.current);
this.current++;
}
this.lock.unlock();
} while (this.current <= this.n);
}
}