Print Even and Odd number using two different thread and Thread interrupt() mechanism

Printing even and odd numbers using two different thread is very basic java interview question from Thread handling. We have discussed it here - Print Even and Odd number using two different thread . The main agenda of this post is to display even and odd numbers using Thread interrupt() mechanism. In other words, two threads will be sleeping for infinite time and and interrupt is send periodically to both thread and on interruption they wake-up and complete the task. Below are the sample code lines discussing the same.
package com.devinline.thread;

public class EvenOddUsingInterrupt {
 public static volatile int counter;

 public static void main(String[] args) throws Exception {
  Thread even = new Thread(new EvenProducer(), "Even");
  Thread odd = new Thread(new OddProducer(), "Odd");
  even.start();
  odd.start();
  while (true) {
   counter++;
   even.interrupt();
   odd.interrupt();
   Thread.sleep(1000L);
  }
 }

 private static class EvenProducer implements Runnable {
  public void run() {
   int oldNum = 0;
   while (true) {
    try {
     Thread.sleep(Long.MAX_VALUE);
    } catch (InterruptedException e) {
     // System.out.println("Interrupted even thread");
    }
    int num = counter;
    if (num != oldNum && num % 2 == 0) {
     System.out.println(Thread.currentThread().getName()
       + " thread produced  " + num);
     oldNum = num;
    }
   }
  }
 }

 private static class OddProducer implements Runnable {
  public void run() {
   int oldNum = 0;
   while (true) {
    try {
     Thread.sleep(Long.MAX_VALUE);
    } catch (InterruptedException e) {
     // System.out.println("Interrupted odd thread");
    }
    int num = counter;
    if (oldNum != num && num % 2 == 1) {
     System.out.println(Thread.currentThread().getName()
       + " thread produced  " + num);
     oldNum = num;
    }
   }
  }
 }
}
=====Sample output=======
Odd thread produced  1
Even thread produced  2
Odd thread produced  3
Even thread produced  4
Odd thread produced  5
Even thread produced  6
Odd thread produced  7
Even thread produced  8
.......
=====================

1 Comments

Previous Post Next Post