我有兩個線程,一個設置類的變量,另一個通過get方法訪問變量。通過兩個不同的線程設置和訪問varibale
public class Parent {
private int value = -1
public int getValue()
return this.value;
}
public void setValue(int value){
this.value = value;
}
private class UpdatingVaribale extends Thread {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
setValue(2);
Thread.currentThread().interrupt();
}
}
}
}
private class GettingVaribale extends Thread {
public void run() {
while (getValue == -1) {
try{
System.out.println(getValue);
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
System.out.println(getValue);
}
}
的問題是,在第二線程中的while
循環的條件總是true
。 System.out.println(getValue)
總是打印-1
。我想知道爲什麼第二個線程沒有得到value
的新值,即2
。我不認爲這裏很重要,因爲一個線程正在設置一個變量,另一個線程正在訪問變量。
的可能的複製[你曾經使用Java中的volatile關鍵字?](http://stackoverflow.com/questions/106591/do-you-ever-使用volatile-keyword-in-java) – shmosel
'synchronized'實際上可以解決你的問題,就像'volatile'或'AtomicInteger'一樣。線程安全不僅僅是競賽條件。 – shmosel
@shmosel,因爲什麼時候它不會構成一個線程對不同線程寫入變量的非同步讀取的競爭條件?但是,是的,您列舉的幾種同步機制中的任何一種都可以解決問題。 –