|
| 1 | +package com.baeldung.concurrent.evenandodd; |
| 2 | + |
| 3 | +public class PrintEvenOdd { |
| 4 | + |
| 5 | + public static void main(String... args) { |
| 6 | + Printer print = new Printer(); |
| 7 | + Thread t1 = new Thread(new TaskEvenOdd(print, 10, false)); |
| 8 | + t1.setName("Odd"); |
| 9 | + Thread t2 = new Thread(new TaskEvenOdd(print, 10, true)); |
| 10 | + t2.setName("Even"); |
| 11 | + t1.start(); |
| 12 | + t2.start(); |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +class TaskEvenOdd implements Runnable { |
| 17 | + private int max; |
| 18 | + private Printer print; |
| 19 | + private boolean isEvenNumber; |
| 20 | + |
| 21 | + TaskEvenOdd(Printer print, int max, boolean isEvenNumber) { |
| 22 | + this.print = print; |
| 23 | + this.max = max; |
| 24 | + this.isEvenNumber = isEvenNumber; |
| 25 | + } |
| 26 | + |
| 27 | + @Override |
| 28 | + public void run() { |
| 29 | + int number = isEvenNumber == true ? 2 : 1; |
| 30 | + while (number <= max) { |
| 31 | + if (isEvenNumber) { |
| 32 | + print.printEven(number); |
| 33 | + } else { |
| 34 | + print.printOdd(number); |
| 35 | + } |
| 36 | + number += 2; |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +class Printer { |
| 42 | + boolean isOdd = false; |
| 43 | + |
| 44 | + synchronized void printEven(int number) { |
| 45 | + while (isOdd == false) { |
| 46 | + try { |
| 47 | + wait(); |
| 48 | + } catch (InterruptedException e) { |
| 49 | + e.printStackTrace(); |
| 50 | + } |
| 51 | + } |
| 52 | + System.out.println(Thread.currentThread() |
| 53 | + .getName() + ":" + number); |
| 54 | + isOdd = false; |
| 55 | + notify(); |
| 56 | + } |
| 57 | + |
| 58 | + synchronized void printOdd(int number) { |
| 59 | + while (isOdd == true) { |
| 60 | + try { |
| 61 | + wait(); |
| 62 | + } catch (InterruptedException e) { |
| 63 | + e.printStackTrace(); |
| 64 | + } |
| 65 | + } |
| 66 | + System.out.println(Thread.currentThread() |
| 67 | + .getName() + ":" + number); |
| 68 | + isOdd = true; |
| 69 | + notify(); |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments