Thursday, August 22, 2019

Print Even Odd Using Two Threads In Java

In the below program i am using reminder. if reminder is 0 (Zero) it will print Even number else if reminder is 1 then it will print Odd number.

public class EvenOdd implements Runnable {

 public int printMaxNum = 10;
 static int num = 1;
 int remainder;
 static Object lockObject = new Object();

 EvenOdd(int remainder) {
  this.remainder = remainder;
 }

 @Override
 public void run() {
  while (num < printMaxNum - 1) {
   synchronized (lockObject) {
    while (num % 2 != remainder) { // wait for numbers other than remainder
     try {
      lockObject.wait();
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
    System.out.println(Thread.currentThread().getName() + " " + num);
    num++;
    lockObject.notifyAll();
   }
  }
 }
}

public class PrintEvenOddNumber {

 public static void main(String[] args) {

  EvenOdd runnable1 = new EvenOdd(0);
  EvenOdd runnable2 = new EvenOdd(1);

  Thread t1 = new Thread(runnable1, "Even");
  Thread t2 = new Thread(runnable2, "Odd");

  t1.start();
  t2.start();
 }
}
Output:

Odd 1
Even 2
Odd 3
Even 4
Odd 5
Even 6
Odd 7
Even 8
Note:- Why i take static object in the above program. because i want to lock on same object while calling two threads.
static object are initialized only once and live until the program terminates.
Local object is created each time its declaration is encountered in the execution of program. static objects are allocated storage in static storage area.

No comments:

Post a Comment