简体   繁体   English

Java多线程,同步概念

[英]Java Multi threading , synchronization concept

I have a class which is having three methods m1,m2 and m3.我有一个具有三种方法 m1、m2 和 m3 的类。 And methods m1,m3 are synchronized.并且方法 m1,m3 是同步的。

Created three threads lets say t1,t2 and t3.创建了三个线程,比如 t1、t2 和 t3。

Here the question is If t1 is accessing m1 method and at the same time can t2 access m3 method?这里的问题是如果t1正在访问m1方法,同时t2可以访问m3方法吗? (both m1 and m3 methods are synchronized). (m1 和 m3 方法都是同步的)。

I don't have code .我没有代码。 Faced this question in my recent interview.在我最近的采访中遇到了这个问题。

if both m1 and m3 are instance methods and not static:如果 m1 和 m3 都是实例方法而不是静态方法:

It would depend on whether t1 and t2 are sharing the same object of your class.这将取决于 t1 和 t2 是否共享您班级的同一对象。 If they are sharing the same object, then t1 and t2 cannot call synchronized methods simultaneously.如果它们共享同一个对象,则 t1 和 t2 不能同时调用同步方法。 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.否则,如果 t1 和 t2 具有不同的类对象副本,则可以同时调用 m1 和 m3,因为它们是 2 个不同的对象。

However, if both m1 and m3 are static: no 2 threads can call them simultaneously ever.但是,如果 m1 和 m3 都是静态的:没有两个线程可以同时调用它们。 This is because, static methods are synchronized on the YourClass.class object, which is shared by all the instance of the class.这是因为,静态方法在 YourClass.class 对象上同步,该对象由类的所有实例共享。 thus, multiple threads cannot access it's synchronized methods/blocks simultaneously.因此,多个线程不能同时访问它的同步方法/块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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