The result of the following code is always: 1 2 3 1 2 3
WHY? I thought the result is unpredictable.
how does synchronized blocks works? I thought synchronized(a) line locks only object on reference "a", but it lock on "b" too.
Tom Mark wrote: I thought synchronized(a) line locks only object on reference "a"
your thought is correct! except it is not with reference instead with object. you created two threads on single object, hence the two threads share the instance object A. so, if one thread acquired the lock of A object, another have to wait until the former thread release the lock on the A object.
Tom Mark wrote:
Line synchronized(a) locks only A object which means that two threads can't access method void doTask1 concurrently
which means if two threads share a common object *a* and if it is synchronized , then both cant enter parallely into the block. one have to wait for other to exit from that block.that's all. *void doTask1 method is not called from synchronized block right?*
Actually in order to access a portion of code , it does not need the object for the portion of code.
'a' in this case is something like a kind of resource, in order to enter the code portion, you need the lock/ resouce , it does not actually require any specific object to enter, as long as the lock can mutually block (thread) each other. in this case, 'a' object is successfully blocking the two concurrent thread.
this is my rookie explanation. need more expert to clarify . haha..
Joined: Jun 15, 2011
But we can write
and we'll get the same result. Why do we need a?
And what if we try to invoke a.doTask1() method by different threads?
I'm trying to figure out how statement
affects accessibility of object "a" which has method doTask1();