JAVA同步块中Wait/Notify的使用

问题描述 投票:0回答:0

我正在尝试调试多线程情况,似乎以下同步块不起作用,但是 实际上,方法中定义的局部变量指向所有线程的同一对象的引用,您有何看法?

锁定对象(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();
            }
        }
    }
    
}
java multithreading synchronization thread-safety thread-synchronization
© www.soinside.com 2019 - 2024. All rights reserved.