简体   繁体   中英

Java Multi threading , synchronization concept

I have a class which is having three methods m1,m2 and m3. And methods m1,m3 are synchronized.

Created three threads lets say t1,t2 and t3.

Here the question is If t1 is accessing m1 method and at the same time can t2 access m3 method? (both m1 and m3 methods are synchronized).

I don't have code . Faced this question in my recent interview.

if both m1 and m3 are instance methods and not static:

It would depend on whether t1 and t2 are sharing the same object of your class. If they are sharing the same object, then t1 and t2 cannot call synchronized methods simultaneously. Otherwise, if t1 and t2 have different copies of your classes objects then, m1 and m3 can be called simultaneously as these are 2 different objects.

However, if both m1 and m3 are static: no 2 threads can call them simultaneously ever. This is because, static methods are synchronized on the YourClass.class object, which is shared by all the instance of the class. thus, multiple threads cannot access it's synchronized methods/blocks simultaneously.

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