我想同步通过ExecutorService调用的3个线程。我如何确保它们在同一个对象上同步?这些线程同步的对象
现在我有这样的代码:
class Test {
executor.submit(new Request(threadNames[i]));
executor.submit(new Request(threadNames[i]));
executor.submit(new Request(threadNames[i]));
private class Request implements Callable {
@Override
public Long call() throws InterruptedException {
if (threadName.equals("SOMETHING") {
doSomething();
} else {
doSomeOtherThing();
}
}
}
private synchronized void doSomething() {
}
private synchronized void doSomeOtherThing() {
}
...
}
其中一个线程负责生成条件和其他2行为就可以了。
用于同步'doSomething'和'doSomeOtherThing'的锁将在创建'Request'的'Test'的实例中。很难确切地说出发生了什么,因为你的代码是不完整的,并且不能以其当前形式工作 - 执行程序调用在“测试”类 –