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?
-
\$\begingroup\$ Nothing to do with code itself, but it might be a good idea te read up on some style guides for Java, atm this looks very messy....google.github.io/styleguide/javaguide.html#s4-formatting \$\endgroup\$Ludisposed– Ludisposed2018年04月04日 10:17:27 +00:00Commented Apr 4, 2018 at 10:17
1 Answer 1
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.