Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Even and Odd using two Threads in Java

Tags:

I tried the code below. I took this piece of code from some other post which is correct as per the author. But when I try running, it doesn't give me the exact result.

This is mainly to print even and odd values in sequence.

public class PrintEvenOddTester {        public static void main(String ... args){         Printer print = new Printer(false);         Thread t1 = new Thread(new TaskEvenOdd(print));         Thread t2 = new Thread(new TaskEvenOdd(print));         t1.start();         t2.start();     }   }    class TaskEvenOdd implements Runnable {      int number=1;     Printer print;      TaskEvenOdd(Printer print){         this.print = print;     }      @Override     public void run() {          System.out.println("Run method");         while(number<10){              if(number%2 == 0){                 System.out.println("Number is :"+ number);                 print.printEven(number);                 number+=2;             }             else {                 System.out.println("Number is :"+ number);                 print.printOdd(number);                 number+=2;             }         }        }      }  class Printer {      boolean isOdd;      Printer(boolean isOdd){         this.isOdd = isOdd;     }      synchronized void printEven(int number) {          while(isOdd){             try {                 wait();             } catch (InterruptedException e) {                 e.printStackTrace();             }         }         System.out.println("Even:"+number);         isOdd = true;         notifyAll();     }      synchronized void printOdd(int number) {         while(!isOdd){             try {                 wait();             } catch (InterruptedException e) {                 e.printStackTrace();             }         }         System.out.println("Odd:"+number);         isOdd = false;         notifyAll();     }  } 

Can someone help me in fixing this?

EDIT Expected result: Odd:1 Even:2 Odd:3 Even:4 Odd:5 Even:6 Odd:7 Even:8 Odd:9

like image 241
Suvasis Avatar asked May 22 '13 10:05

Suvasis


People also ask

How do you print even odd numbers with two threads?

Since isOdd is false initially, wait() is not called, and the value is printed. We then set the value of isOdd to true, so that the odd thread goes into the wait state and call notify() to wake up the even thread. The even thread then wakes up and prints the even number since the odd flag is false.

How do I make two threads run alternatively?

Create 2 Semaphore s and pass them to 2 threads: Semaphore a = new Semaphore(1); // first thread is allowed to run immediately Semaphore b = new Semaphore(0); // second thread has to wait ThreadPrinter tp1 = new ThreadPrinter(1, a, b); ThreadPrinter tp2 = new ThreadPrinter(2, b, a);


2 Answers

Found the solution. Someone looking for solution to this problem can refer :-)

public class PrintEvenOddTester {      public static void main(String... args) {         Printer print = new Printer();         Thread t1 = new Thread(new TaskEvenOdd(print, 10, false));         Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));         t1.start();         t2.start();     }  }  class TaskEvenOdd implements Runnable {      private int max;     private Printer print;     private boolean isEvenNumber;      TaskEvenOdd(Printer print, int max, boolean isEvenNumber) {         this.print = print;         this.max = max;         this.isEvenNumber = isEvenNumber;     }      @Override     public void run() {          //System.out.println("Run method");         int number = isEvenNumber == true ? 2 : 1;         while (number <= max) {              if (isEvenNumber) {                 //System.out.println("Even :"+ Thread.currentThread().getName());                 print.printEven(number);                 //number+=2;             } else {                 //System.out.println("Odd :"+ Thread.currentThread().getName());                 print.printOdd(number);                 // number+=2;             }             number += 2;         }      }  }  class Printer {      boolean isOdd = false;      synchronized void printEven(int number) {          while (isOdd == false) {             try {                 wait();             } catch (InterruptedException e) {                 e.printStackTrace();             }         }         System.out.println("Even:" + number);         isOdd = false;         notifyAll();     }      synchronized void printOdd(int number) {         while (isOdd == true) {             try {                 wait();             } catch (InterruptedException e) {                 e.printStackTrace();             }         }         System.out.println("Odd:" + number);         isOdd = true;         notifyAll();     }  } 

This gives output like:

Odd:1 Even:2 Odd:3 Even:4 Odd:5 Even:6 Odd:7 Even:8 Odd:9 Even:10 
like image 189
Suvasis Avatar answered Jan 25 '23 03:01

Suvasis


Use this following very simple JAVA 8 Runnable Class feature

public class MultiThreadExample {  static AtomicInteger atomicNumber = new AtomicInteger(1);  public static void main(String[] args) {     Runnable print = () -> {         while (atomicNumber.get() < 10) {             synchronized (atomicNumber) {                 if ((atomicNumber.get() % 2 == 0) && "Even".equals(Thread.currentThread().getName())) {                     System.out.println("Even" + ":" + atomicNumber.getAndIncrement());                 } //else if ((atomicNumber.get() % 2 != 0) && "Odd".equals(Thread.currentThread().getName()))                    else {System.out.println("Odd" + ":" + atomicNumber.getAndIncrement());                 }             }         }     };      Thread t1 = new Thread(print);     t1.setName("Even");     t1.start();     Thread t2 = new Thread(print);     t2.setName("Odd");     t2.start();  } } 
like image 32
Raj Ved Avatar answered Jan 25 '23 04:01

Raj Ved