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.
Read about class and instance level locks in Java. Its good from interview perspective also.
Line synchronized(a) locks only A object which means that two threads can't access method void doTask1 concurrently, but they can
access code concurrently in the following code:
because the lock is on A, not on synchronized(this)
That means that the result could be 112233 or else.
I know that I'm wrong, but I don't know why.
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?*
you can go through this tutorial
'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..
Tom Mark wrote:But we can write
and we'll get the same result.
Correct! , if you are not consider doTask1() method accessibility!
Tom Mark wrote:
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();
when the both the thread holds a's lock, no other thread(say example:main thread) can enter into doTask1 *if it is synchronized*
consider below scenario