我正在尝试调试多线程情况,似乎以下同步块不起作用,但是 实际上,方法中定义的局部变量指向所有线程的同一对象的引用,您有何看法?
锁定对象(dummyStack)上的弹出和推送操作是否会导致监控密钥发生变化并导致同步损坏?
public class ResourceCache { {
private SynchronousStack dummySyncStack; // Same object for all threads.
// It will be filled with resource.
// Threads gets resource from it and push back after they jobs finished.
protected Resource getResource() {
Stack dummyStack = dummySyncStack;
Resource r = null;
if( dummyStack != null ) {
synchronized(dummyStack) { // Multiple threads can enter to inside this block at the
//same time, idk why.
if( dummyStack.isEmpty() ) {
try {
dummyStack.wait(5000);
}
catch(InterruptedException ex) {
}
}
r = (Resource) dummyStack.pop();
}
}
return r;
}
protected void restoreResource(Resource freeResource) {
Stack dummyStack = dummySyncStack;
if(dummyStack != null) {
synchronized(dummyStack) {
dummyStack.push(freeResource);
dummyStack.notify();
}
}
}
}