[英]Access flags in synchronized methods?
我在瀏覽大學班的一些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
之后而不是之前更改的原因)
編輯 :另一個問題:所有這些代碼中有什么意義嗎? 我的意思是,它所做的就是獲取並將向量添加到向量中。 這些動作不是已經在矢量上同步了嗎? 所有這些代碼只是為了讓我們得到一些打印?
我同意-鑒於方法已標記為同步,因此無需進行這些額外的檢查。
(看起來有人想要真的非常確定沒有同步問題。:-)
具有諷刺意味的是,可以說canAccess
不是線程安全的。 因此,即使沒有同步方法,也不一定是合適的選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.