假设我有两个线程,都从给定的类实例 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();
}
}
我仍然不确定我做错了什么。
最佳答案
同步
方法是一种快捷方式。 IMO,在开始使用快捷方式之前,您应该先学会如何做到这一点:
如果你有这个:
class A {
synchronized SomeType myMethod(...) {
doSomeStuff(...);
...
return someThing;
}
}
这是编写顶级 synchronized statement 的方法声明的快捷方式:
class A {
SomeType myMethod(...) {
synchronized (this) {
doSomeStuff(...);
...
return someThing;
}
}
}
IMO,您应该首先学习如何使用同步语句,然后只有在更好地理解同步语句如何工作时才使用同步方法。
关于java - 如何防止同一类实例中的不同线程同时执行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53591917/