【发布时间】:2018-12-03 10:33:35
【问题描述】:
假设我有两个线程,都从给定的类实例 A 开始。线程必须从同一个实例执行一个方法,但一次一个。我尝试使该方法同步,但显然它适用于尝试调用该方法的不同实例(据我了解;如果我错了,请原谅我)。
那么,我应该如何实现这一点,最好采用标准或推荐的方式?
编辑:这是相关代码:
public class A {
.
.
.
public void method1(){
ExecutorService threadObject = Executors.newSingleThreadExecutor();
threadObject.execute(new Runnable(){
@Override
public void run() {
try {
while (someCondition) {
//Here's one invocation
someObject = readObject();
}
}
catch (IOException | ClassNotFoundException ex) {}
}
});
//Here's the other invocation
while(someCondition){
someObject = readObject();
}
}
//Here's the synchronized method
private synchronized SomeClass readObject() throws IOException, ClassNotFoundException{
return (SomeClass) incomingResponses.readObject();
}
//Main method to instantiate the class
public static void main(String ... args) {
A = new A();
A.method1();
}
}
我仍然不确定我做错了什么。
【问题讨论】:
-
请发布您的同步代码。
-
@AlexeySoshin 我已经添加了相关代码。
-
我在你的代码中看不到 2 个线程在 A 的同一个实例上工作。我只看到 1 个线程,没有 A 的实例。
-
@AlexeiKaigorodov,同意,示例不完整,但有两个线程:主线程和
threadObject执行程序创建的线程。跨度> -
@AlexeiKaigorodov 抱歉,应该更彻底地审查 sn-ps;希望代码现在更有意义
标签: java multithreading concurrency