0

Printing even odd can be achieved without wait and notify, want understand is wait notify gives better performance over below code ?

  public class EvenOdd {

  public static void main(String[] args) {
    Thread t1= new ThreadToPrint("Even");
    Thread t2= new ThreadToPrint("Odd");
    t1.start();
    t2.start(); 
}
}

class ThreadToPrint extends Thread{
     static Integer count = 0;
     static int MAX = 100;
     static boolean printEven = true;

     public ThreadToPrint(String string) {
        super(string);
     } 

     @Override
    public void run() {
        while (count < MAX) {
                if ("Even".equals(Thread.currentThread().getName()) && printEven) {
                    System.out.println("*************"+Thread.currentThread().getName() + " Printing :" + count++);
                    printEven=false;
                } else if ("Odd".equals(Thread.currentThread().getName()) && !printEven) {
                    System.out.println(Thread.currentThread().getName() + " Printing :" + count++);
                    printEven=true;
                }
          }
      }
    }
varsha
  • 304
  • 8
  • 22
  • Both `count` and `printEven` are shared mutable and they are dependent, you should change `count` and `printEven` atomically. This might not be a problem, because `t2` can't print until it see `t1` change `printEven`, but you'd better do that. Another problem: without synchronization, `t1` might not see the changed made by `t2`. – Jason Law Jan 08 '20 at 08:54
  • Possible duplicate of https://stackoverflow.com/questions/24948791/what-is-fast-wait-notify-or-busy-wait-in-java – Ivan Jan 08 '20 at 18:20
  • Thank you Jason Low ,Agreed on first suggestion .. but i think so without synchronization t1 and t2 able to see changes as shared variables are static .. but concern is do i need to use synchronization to solve this problem? will it be fast with synchronization – varsha Jan 13 '20 at 19:09
  • Thank you Ivan suggested post helped me to understand some concepts. – varsha Jan 13 '20 at 19:17

0 Answers0