1) Does a thread relinquish it's lock as soon as notify is invoked within that threads synchronized code block, or once the synchronized code block is exited?
For instance, it seems like without specifying thread priority, my Process class will execute from top to bottom. Produce will be called first, it will do stuff, then wait(); consume will run, and then it hits notify(), which will print "Done" or will there be a 5 second delay first, then "Done" will be printed?
2) Also, if I had a third synchronized method/thread, that does not wait or notify and just runs, can I predict the order in which my operations are executed a priori?
3) Finally, how does notify() know what thread to 'wake up'? Like, let's say I have multiple Processes each executing 2 threads simultaneously, and each Process A, B, and C evoke notify( ). Is each notify( ) local to each Process? In other words, if Process A calls notify( ), can that wake up a waiting thread in Process B? So far I've seen synchronized called on (this), which makes me think its referring to a particular object class, which in turn makes me think that all notify( )'s called in synchronized blocks are bound by whatever this in synchronized(this) is referring to, so there would be no cross-over.
public class Process {
public void produce( ) {
synchronized(this) {
// do stuff
wait( );
System.out.println("Done");
}
}
public void consume( ) {
synchronized(this) {
// stuff
notify();
Thread.sleep(5000);
}
}
}