|
| 1 | +class FizzBuzz { |
| 2 | + private int n; |
| 3 | + private int count; |
| 4 | + private Semaphore fizz; |
| 5 | + private Semaphore buzz; |
| 6 | + private Semaphore fizzBuzz; |
| 7 | + private Semaphore number; |
| 8 | + |
| 9 | + public FizzBuzz(int n) { |
| 10 | + this.n = n; |
| 11 | + this.count = 1; |
| 12 | + this.fizz = new Semaphore(0); |
| 13 | + this.buzz = new Semaphore(0); |
| 14 | + this.fizzBuzz = new Semaphore(0); |
| 15 | + this.number = new Semaphore(1); |
| 16 | + } |
| 17 | + |
| 18 | + // printFizz.run() outputs "fizz". |
| 19 | + public void fizz(Runnable printFizz) throws InterruptedException { |
| 20 | + while (this.count <= this.n) { |
| 21 | + if (this.count % 3 == 0 && this.count % 5 != 0) { |
| 22 | + this.fizz.acquire(); |
| 23 | + printFizz.run(); |
| 24 | + this.count++; |
| 25 | + releaseLock(this.count); |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + // printBuzz.run() outputs "buzz". |
| 31 | + public void buzz(Runnable printBuzz) throws InterruptedException { |
| 32 | + while (this.count <= this.n) { |
| 33 | + if (this.count % 3 != 0 && this.count % 5 == 0) { |
| 34 | + this.buzz.acquire(); |
| 35 | + printBuzz.run(); |
| 36 | + this.count++; |
| 37 | + releaseLock(this.count); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // printFizzBuzz.run() outputs "fizzbuzz". |
| 43 | + public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException { |
| 44 | + while (this.count <= this.n) { |
| 45 | + if (this.count % 3 == 0 && this.count % 5 == 0) { |
| 46 | + this.fizzBuzz.acquire(); |
| 47 | + printFizzBuzz.run(); |
| 48 | + this.count++; |
| 49 | + releaseLock(this.count); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // printNumber.accept(x) outputs "x", where x is an integer. |
| 55 | + public void number(IntConsumer printNumber) throws InterruptedException { |
| 56 | + while (this.count <= this.n) { |
| 57 | + if (this.count % 3 != 0 && this.count % 5 != 0) { |
| 58 | + this.number.acquire(); |
| 59 | + printNumber.accept(this.count); |
| 60 | + this.count++; |
| 61 | + releaseLock(this.count); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + private void releaseLock(int n) { |
| 67 | + if (n % 15 == 0) { |
| 68 | + this.fizzBuzz.release(); |
| 69 | + } else if (n % 3 == 0) { |
| 70 | + this.fizz.release(); |
| 71 | + } else if (n % 5 == 0) { |
| 72 | + this.buzz.release(); |
| 73 | + } else { |
| 74 | + this.number.release(); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments