java - 多个线程访问同一对象上的同步和非同步方法

标签 java multithreading

假设有一个类Test,它有一个同步方法m1,一个非同步方法m2,以及一个Test的实例,比如obj。两个线程T1和T2,尝试访问与实例obj相关的方法。 当 T1 调用 obj.m1(同步方法)时,在完成 m1 执行之前,T2 调用 obj.m2(非同步方法)时会发生什么情况。 T2需要等待吗?

我在采访中被问到这个问题。

我的回答:T2将继续执行,无需任何等待。 T2正在访问非同步方法,因此不需要任何锁。

面试官似乎并不同意我的回答,尽管当我向他询问我的回答是否正确时,他没有提供任何意见。

如果我遗漏了什么,请帮助我理解。

P.S.我已经尝试过一个测试程序,我发现我的理解是正确的。我只是想知道是否有任何特殊情况,正如我向面试官解释的那样,这不起作用。

最佳答案

嗯,你的回答肯定是正确的,但我想这个小小的回答并没有让面试官高兴,或者他可能有更高的期望并希望对他的问题有一个非常清晰的解释。

我不会编写任何代码来回答您的问题,但我将陈述两点,重点介绍 java 中的多线程 的基础知识。

1) Each object has only one lock.

2) If two threads say T1 and T2 are trying to execute synchronized instance methods on the same object, then the thread which obtains the lock first will be able to execute the synchronized method and the other thread T2 will have to wait until T1 completes its execution or enters into blocking/waiting state for some handful number of reasons. In other words, No Thread T2 can not enter ANY (I repeat ANY) synchronized method for an object "obj" if Thread T1 already has a lock for the same object obj.

3) If a Class has both synchronized and non-synchronized methods, then any number of Threads can access the non-synchronized methods in any way they wish without having to wait for someone or something.

这里的底线是,线程 T2 不需要等待线程 T1 完成其执行,因为它正在尝试执行非同步方法。希望这个答案符合您的期望。

我看到您已经编辑了您的问题

P.S. I have tried a test program already, and I see that my understanding is right. I am just wondering if there is any special scenario where this would not work as I explained to the interviewer.
There is no such scenario. The above points should meet your question.

关于java - 多个线程访问同一对象上的同步和非同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42887992/

相关文章:

Java:如何启动一些异步操作并从其他线程更新用户界面?

java - Eclipse Oxygen 此编译单元不在 java 项目的构建路径上

java - "org.eclipse.equinox.ds@3:start"背后的魔力?

c++ - 无法在 C++ 中使用多线程

java - 无法在 Unity3D 中调用 native Android 代码

java - OpenCV Java : Compare Bounding Rect's y value, 清除不需要的

VB.Net:了解 Application.Run() 的工作方式

java - 通过线程中的套接字进行对象输入/输出

c - OpenMP:任务中的竞争条件

java - 多线程同步