假设我有两个线程,都是从给定的类实例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();
}
}
我仍然不确定我做错了什么 .
2 回答
synchronized
方法是一种捷径 . IMO,在开始使用快捷方式之前,您应该学会很长时间:如果你有这个:
这是使用顶级synchronized statement编写方法声明的快捷方式:
IMO,您应该首先学习如何使用synchronized语句,然后在更好地理解synchronized语句的工作方式时使用synchronized方法 .
你的陈述是错的 . 引用documentation中的相关示例:
因此,在方法上应用
synchrinzed
关键字将不允许在特定对象实例上并发调用该方法 .