1
\$\begingroup\$

I have written a program which creates a 2 new thread and shares a common lock object to print numbers alternatively. Wanted to know if the approach for using wait() and notify() is correct?

Main Class

public class MyMain {
public static void main(String[] args) {
MyThread1 obj = new MyThread1();
Thread thread1 = new Thread(obj);
Thread thread2 = new Thread(obj);

thread1.setName("t1");
thread2.setName("t2");

thread1.start();
thread2.start();

}
}

Thread Class

public class MyThread1 implements Runnable{
int i = 0;
@Override
public synchronized void run() {
    while(i<10)
    {
        if(i%2==0)
        {   
try{
                notify();
                System.out.println(Thread.currentThread().getName()+" prints "+i);
                i++;
                wait();

             }catch(Exception e){ e.printStackTrace(); }
        }else
        {
            try{
                notify();
                System.out.println(Thread.currentThread().getName()+" prints "+i);
                i++;
                wait();
            }catch(Exception e){ e.printStackTrace(); }
        }
    }
}
}

Can there be a better usage of wait() and notify() instead of using it in both the if conditions?

\$\endgroup\$
1

1 Answer 1

3
\$\begingroup\$

I'm not sure what you expect from writing an if-else construct where both the if and the else block contain exactly the same code. Your run() method is effectively equivalent to the following:

public synchronized void run() {
    while (i < 10) {
        try {
            notify();
            System.out.println(Thread.currentThread().getName() + " prints " + i);
            i++;
            wait();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Other than that, your usage of notify() and wait() looks fine. However, there is a phenomenon called a "spurious wakeup", which means that a thread can be awakened for no apparent reason at all. This is very unlikely, but theoretically, it is possible that one of your two threads is spuriously woken up after it enters the waiting state but before the other thread acquires the lock on obj, which could result in one thread printing two consecutive numbers if the thread that was spuriously woken up re-acquires the lock. You might take a look at this.

Also, your program never terminates. You can rectify this by calling notify() or notifyAll() after the while loop.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.