同步方法中的访问标志?

时间:2012-01-21 21:10:34

标签: java methods synchronized

我在大学课堂上看了一些pdf,我注意到了这段代码:

public class MyMemoryElements {
    private String x = "";

    public MyMemoryElements(String message){
        this.x = message;
    }

    @Override
    public boolean equals(Object o){
        if(o instanceof MyMemoryElements ){
            MyMemoryElements tmp = (MyMemoryElements)o;
            if(tmp.toString().equalsIgnoreCase(this.x))
               return true;
            return false;
        }
        return false;

    }

    @Override
    public String toString(){
        return this.x;
   }
}

和主要代码:

public class MainMemory {
   private Vector<MyMemoryElements> storage;
   private boolean canAccess = true;
   private int counter = -1;

   public MainMemory(){
       storage = new Vector<MyMemoryElements>();
   }

   public synchronized MyMemoryElements take(String s) {
       System.out.print("Method take has been invoked by "+s+". Element is:");
       while (!canAccess || storage.size()==counter+1) {
           try {
               wait();
           } catch (InterruptedException e) {}
       }
       canAccess = false;
       counter++;
       MyMemoryElements x = storage.elementAt(counter);
       try {
           Thread.sleep(10000);
       } catch (InterruptedException ex) {}
       notifyAll();
       System.out.println(x.toString());
       canAccess = true;
       return x;
   }

   public synchronized void update(MyMemoryElements element) {
       System.out.println("Producer is inserting element "+ element.toString());
       while (!canAccess) {
           try { 
               wait();
           } catch (InterruptedException e) {}
       }
       canAccess = false; 
       this.storage.add(element);
       notifyAll();
       canAccess = true;
   }
}

考虑到方法是同步的,我似乎无法理解canAccess变量的需要(也不是 notifyAll之后标志更改而不是之前)的原因

编辑:另一个问题: 所有这些代码中都有任何意义吗?我的意思是它所做的只是获取并向向量添加内容。这些动作不是已经在向量上同步了吗?所有这些代码只是为了我们可以得到一些打印?

1 个答案:

答案 0 :(得分:1)

我同意 - 鉴于这些方法已标记为同步,因此无需进行这些额外检查。

(看起来有人想要真的,确实没有同步问题。: - )

具有讽刺意味的是,可以认为canAccess不是线程安全的。因此,即使没有同步的方法,这也不一定是合适的替代方案。