简体   繁体   中英

Thread Safe Synchronization Block

I have some confusion regarding thread Synchronization . Consider i have two thread Thread1 and Thread2 and two method synchronized foo1() and foo2() . foo1() is synchronized method and foo2() is not, in foo1 internally there is a statement which calls foo2() and if Thread1 calls foo1() and in that it is working in foo2() method, at the same time Thread2 want to access foo2() method directly which is not synchronized.

So my question is will Thread2 get access of Foo2()? or it will wait for Thread1 to complete its task?

If foo2() is not synchronized, any thread can call it any time without being blocked. It doesn't make any difference whether a thread is calling it from another method which is itself synchronized.

It is the object, not the method which is locked. This means you can have the two threads in foo1() if they are accessing different objects. If they are accessing the same object, the same lock will prevent concurrent access regardless of what is called first or what calls it.

BTW: foo1() can call itself as it already has the lock.

Thread2 won't be blocked and won't wait. It will start execution Foo2, since it's not synchronized.

Thread2可以直接调用foo2(),因为foo2()不是同步方法,因此任何线程都可以调用它,而不会获取当前对象的监视器。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM