Threads add a non-deterministic element into program execution which can lead to unexpected output, even corruption of data. Unfortunately, the wait()-notify(), as presented
does not provide sufficient support for the programmer. Indeed, as presented, it adds
additional complications.
Consider this linked example.Question: What happens, if the first Thread to run finishes its time-slice after
notify() but before wait()?
Is it possible for both threads to go into a wait state, a deadlock?
The answer is no! The reason is that the key word synchronized.
The rules of synchronization are as follows:
- Synchronization locks are allocated on a One per object basis (class object or instance object)
- For each object, only one thread executing a synchronized method can hold the lock at any time. Threads executing synchronized static methods hold the class object lock.
- Locks are only released by
- Normal method completion.
- Abrupt method completion.
- Invoking a wait().
- If a method is blocked in by a wait(). It can be returned to the "can_run/run" state if
- Some other synchronized thread of the object invokes notify() and the thread whose method is blocked happens to be the one chosen. There are no protocols for choosing this tread.
- notifyAll() is invoked, which unblocks all synchronized threads of the object.