What does it mean when a thread moves out of an object's monitor?
All I want to know is that when a thread enters out of a lock, does it means it "ends" or just that it has finished usi开发者_C百科ng that function or code which employed the use of the object whose monitor that particular thread is in?
Just that it has finished using that function or code which employed the use of the object. Such pieces of code are commonly known as critical section(s).
For your general understanding: methods run on threads. So it is possible that one method is being executed by multiple threads at the same time.
Imagine you want to make sure that a method, or part of it, can only be executed by one thread at a time. This is called a critical section.
A critical section in Java can be protected by a lock: implicitly via synchronized or explicitly via java.util.concurrent.locks.
Only one thread at a time can acquire the lock and entering the critical section requires that the lock be acquired first. At the end of the critical section the lock is released and the thread continues running but now without holding that lock.
A thread encountering a lock held by another thread (not necessarily for the same critical section) cannot proceed at that point and must wait. The thread, and other threads waiting on the same lock, will be notified when they can retry to acquire the lock. Again, only one thread will win and the process repeats (unless you have a deadlock for example).
精彩评论