I have a thread that calls the wait
method and can only be awoken when the notify
method called from some other class:
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
synchronized(b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
}
}
}
class ThreadB extends Thread {
int total;
public void run() {
synchronized(this) {
for(int i=0;i<100;i++) {
total += i;
}
notify();
}
}
}
In the above code if the synchronized
block in main
, if the ThreadA
does not execute first and instead the other synchronization block executing and completes to completion, then ThreadA
executes its synchronized
block and calls wait
, what is going to happen and how it will be notified again?
You probably want to use a java.util.concurrent.Semaphore for this.
If
ThreadB
gets through itssynchronized
block beforeThreadA
does, thenThreadA
will block indefinitely on the call towait
. It won't somehow be notified that the other thread has already completed.The problem is that you're trying to use
wait
andnotify
in ways that they are not designed to be used. Usually,wait
andnotify
are used to have one thread wait until some condition is true, and then to have another thread signal that the condition may have become true. For example, they're often used as follows:The reason that the above code works is that it doesn't matter which thread runs first. If the producer thread creates a resource and no one is
wait
ing onobj
, then when the consumer runs it will enter thewhile
loop, notice that the resource has been produced, and then skip the call towait
. It can then consume the resource. If, on the other hand, the consumer runs first, it will notice in thewhile
loop that the resource is not yet available and willwait
for some other object to notify it. The other thread can then run, produce the resource, andnotify
the consumer thread that the resource is available. Once the original thread is awoken, it will notice that the condition of the loop is no longer true and will consume the resource.More generally, Java suggests that you always call
wait
in a loop because of spurious notifications in which a thread can wake up from a call towait
without ever being notified of anything. Using the above pattern can prevent this.In your particular instance, if you want to ensure that
ThreadB
has finished running beforeThreadA
executes, you may want to useThread.join()
, which explicitly blocks the calling thread until some other thread executes. More generally, you may want to look into some of the other synchronization primitives provided by Java, as they often are much easier to use thanwait
andnotify
.It is possible for ThreadB's run method to complete before you enter the synchronized block in ThreadA.main. In that situation, since the notify call has happened before you started waiting, ThreadA will block forever on the wait call.
A simple workaround would be to grab the lock on b in main before you start the second thread to ensure the wait happens first.
do not
synchronized(thread)
, don't do it, do notsynchronized(thread)
.. repat: nosynchronized(thread)
:)And if you need to wait for the thread 'b' to finish, use b.join(), now your code is free to hang in b.wait()
--
Hopefully the source below can grant you an insight while sync(thread)/notify() I consider bad practice. (cut-cut)
Enjoy
To proceeed below you make sure you have accepted Oracle's License aggreement, found there: https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewLicense-Start?LicenseUUID=7HeJ_hCwhb4AAAEtmC8ADqmR&ProductUUID=pGqJ_hCwj_AAAAEtB8oADqmS&cnum=&evsref=&sln=
Java sources (incl), called in init(), effectively called by any java c-tor, since java 1.5
//join (the method w/ nanos only increase millis by one, if nanos>500000, millis==0 and nanos>0
//stop1 is called after stop ensures proper priviledges
1) You need to add some flag that is used to communicate between the threads, so that B can signal to A when it is finished. A simple boolean variable is fine, as long as it is only read and written within the synchronized blocks.
2) A needs to loop while waiting. So if your boolean variable was called isDone, and was set to true by threadB, then threadA should have some code like this:
In this particular case, there's actually no reason to have the synchronized block in A - since threadB doesn't do anything after it finishes running, and A doesn't do anything except wait for B, threadA could simply call b.join() to block until it finishes. I assume that your actual use case is more complex than this.
You could loop and wait until the total has been computed :
You could also use a higher-level abstraction like a CountDownLatch.