Wednesday, 26 September 2018

Odd Even switch using java multithreading


Consider there are two threads,
Even Thread
- Print only Even numbers
Odd Thread
- Print only Odd numbers
Print numbers from 1 to 50 by switching Odd and Even Threads,
Approach:
step 1. Create each threads with synchronized block
step 2. Create Monitor object with shared thread status and shared number
step 3. loop through mo.number and wait or execute based on the shared thread status
 
      Even.java  
public class Even implements Runnable { private static MonitorObject mo = new MonitorObject(); public Even(MonitorObject mo) { this.mo = mo; } public void run() { try { synchronized (mo) { while (mo.number <= 50) { if (!mo.isEven) { mo.wait(); } else { if (mo.number % 2 == 0) { System.out.println(mo.number); } mo.number++; mo.isEven = false; mo.notifyAll(); } } } } catch (InterruptedException e) { e.printStackTrace(); } } }
 
      Odd.java  
public class Odd implements Runnable { private static MonitorObject mo = new MonitorObject(); public Odd(MonitorObject mo) { this.mo = mo; } public void run() { try { synchronized (mo) { while (mo.number <= 50) { if (mo.isEven) { mo.wait(); } else { if (mo.number % 2 != 0) { System.out.println(mo.number); } mo.isEven = true; mo.number++; mo.notifyAll(); } } } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
 
      MonitorObject.java  
public class MonitorObject { public static boolean isEven = false; public static int number = 0; }
 
      App.java  
public class App { private static MonitorObject mo = new MonitorObject(); public static void main(String[] args) { mo.isEven = true; Thread even = new Thread(new Even(mo)); even.start(); Thread odd = new Thread(new Odd(mo)); odd.start(); } } /* ****** OUTPUT ******** 0,1,2,3,4,5,6,7,8,9... ******* OUTPUT ******** */

No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *