Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class FizzBuzz {
- private int n;
- private int counter;
- private boolean complete;
- public FizzBuzz(int n) {
- this.n = n;
- this.counter = 1;
- this.complete = false;
- }
- // printFizz.run() outputs "fizz".
- public synchronized void fizz(Runnable printFizz) throws InterruptedException {
- while((counter % 3 != 0 || counter % 5 == 0) && !complete) {
- wait();
- }
- while (!complete) {
- printFizz.run();
- incrementAndValidateCounter();
- if (complete) {
- notifyAll();
- break;
- }
- boolean first = true;
- while((counter % 3 != 0 || counter % 5 == 0) && !complete) {
- if (first) {
- notifyAll();
- first = false;
- }
- wait();
- }
- }
- }
- // printBuzz.run() outputs "buzz".
- public synchronized void buzz(Runnable printBuzz) throws InterruptedException {
- while((counter % 3 == 0 || counter % 5 != 0) && !complete) {
- wait();
- }
- while (!complete) {
- printBuzz.run();
- incrementAndValidateCounter();
- if (complete) {
- notifyAll();
- break;
- }
- boolean first = true;
- while((counter % 3 == 0 || counter % 5 != 0) && !complete) {
- if (first) {
- notifyAll();
- first = false;
- }
- wait();
- }
- }
- }
- // printFizzBuzz.run() outputs "fizzbuzz".
- public synchronized void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
- while((counter % 3 != 0 || counter % 5 != 0) && !complete) {
- wait();
- }
- while (!complete) {
- printFizzBuzz.run();
- incrementAndValidateCounter();
- if (complete) {
- notifyAll();
- break;
- }
- boolean first = true;
- while((counter % 3 != 0 || counter % 5 != 0) && !complete) {
- if (first) {
- notifyAll();
- first = false;
- }
- wait();
- }
- }
- }
- // printNumber.accept(x) outputs "x", where x is an integer.
- public synchronized void number(IntConsumer printNumber) throws InterruptedException {
- while((counter % 3 == 0 || counter % 5 == 0) && !complete) {
- wait();
- }
- while (!complete) {
- printNumber.accept(counter);
- incrementAndValidateCounter();
- if (complete) {
- notifyAll();
- break;
- }
- boolean first = true;
- while((counter % 3 == 0 || counter % 5 == 0) && !complete) {
- if (first) {
- notifyAll();
- first = false;
- }
- wait();
- }
- }
- }
- private void incrementAndValidateCounter() {
- ++counter;
- if (counter > n) {
- complete = true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement