Re: a simple multi-thread question
On 1/26/2015 10:40 AM, John wrote:
I am amazed at what I saw:
synchronized private void print()
{
System.out.println("printing A");
System.out.println("printing B");
System.out.println("printing C");
}
[... he gets interleaved output ...]
Each Java object has its own lock ("monitor"), independent of the
locks belonging to other Java objects. When you call a synchronized
instance method, Java acquires the lock of the "this" object before
proceeding, and releases it when the method finishes. If there are
several object instances floating around, there are several "this"
and several independent locks.
I thought the method is atomic.
No. Synchronization is not about methods (or code blocks), but
about objects: You lock the *object*, not a method. If there are
four baristas at the Starcrossed shop, you "lock" only one of them
while placing your order, you do not "lock" the entire place-an-order
procedure and keep other customers from being serviced.
Time to re-open your textbook, I think.
--
esosman@comcast-dot-net.invalid
"Don't be afraid of work. Make work afraid of you." -- TLM