Java Reference
In-Depth Information
public final void notify ()
public final void notifyAll ()
These must be invoked on the object the thread was waiting on, not generally on the
Thread itself. Before notifying an object, a thread must first obtain the lock on the object
using a synchronized method or block. The notify() method selects one thread more
or less at random from the list of threads waiting on the object and wakes it up. The
notifyAll() method wakes up every thread waiting on the given object.
Once a waiting thread is notified, it attempts to regain the lock of the object it was waiting
on. If it succeeds, execution resumes with the statement immediately following the
invocation of wait() . If it fails, it blocks on the object until its lock becomes available;
then execution resumes with the statement immediately following the invocation of
wait() .
For example, suppose one thread is reading a JAR archive from a network connection.
The first entry in the archive is the manifest file. Another thread might be interested in
the contents of the manifest file even before the rest of the archive is available. The
interested thread could create a custom ManifestFile object, pass a reference to this
object to the thread that would read the JAR archive, and wait on it. The thread reading
the archive would first fill the ManifestFile with entries from the stream, then notify
the ManifestFile , then continue reading the rest of the JAR archive. When the reader
thread notified the ManifestFile , the original thread would wake up and do whatever
it planned to do with the now fully prepared ManifestFile object. The first thread
works something like this:
ManifestFile m = new ManifestFile ();
JarThread t = new JarThread ( m , in );
synchronized ( m ) {
t . start ();
try {
m . wait ();
// work with the manifest file...
} catch ( InterruptedException ex ) {
// handle exception...
}
}
The JarThread class works like this:
ManifestFile theManifest ;
InputStream in ;
public JarThread ( Manifest m , InputStream in ) {
theManifest = m ;
this . in = in ;
}
@Override
Search WWH ::




Custom Search