-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFizzBuzzMultithreaded.java
More file actions
67 lines (48 loc) · 1.74 KB
/
FizzBuzzMultithreaded.java
File metadata and controls
67 lines (48 loc) · 1.74 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
class FizzBuzz {
//Non optimal, threads might waste CPU cycles. Fine grained semaphores would be more suitable
private int n;
private AtomicInteger current = new AtomicInteger(1);
public FizzBuzz(int n) {
this.n = n;
}
// printFizz.run() outputs "fizz".
public void fizz(Runnable printFizz) throws InterruptedException {
int value;
while((value = current.get()) <= n) {
if (value % 3 == 0 && value % 15 != 0) {
printFizz.run();
value = current.incrementAndGet();
}
}
}
// printBuzz.run() outputs "buzz".
public void buzz(Runnable printBuzz) throws InterruptedException {
int value;
while((value = current.get()) <= n) {
if (value % 5 == 0 && value % 15 != 0) {
printBuzz.run();
value = current.incrementAndGet();
}
}
}
// printFizzBuzz.run() outputs "fizzbuzz".
public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
int value;
while((value = current.get()) <= n) {
if (value % 15 == 0) {
printFizzBuzz.run();
value = current.incrementAndGet();
}
}
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void number(IntConsumer printNumber) throws InterruptedException {
int value;
while((value = current.get()) <= n) {
if (value % 3 != 0 && value % 5 != 0) {
printNumber.accept(value);
value = current.incrementAndGet();
}
}
}
}