私が理解しているように、変数を揮発性として宣言すると、ローカルキャッシュに保存されません。スレッドが値を更新するたびに、メイン メモリに更新されます。したがって、他のスレッドは更新された値にアクセスできます。
しかし、次のプログラムでは、揮発性変数と非揮発性変数の両方が同じ値を表示しています。
2 番目のスレッドの volatile 変数は更新されません。testValue が変更されない理由を誰でも説明できますか。
class ExampleThread extends Thread {
private int testValue1;
private volatile int testValue;
public ExampleThread(String str){
super(str);
}
public void run() {
if (getName().equals("Thread 1 "))
{
testValue = 10;
testValue1= 10;
System.out.println( "Thread 1 testValue1 : " + testValue1);
System.out.println( "Thread 1 testValue : " + testValue);
}
if (getName().equals("Thread 2 "))
{
System.out.println( "Thread 2 testValue1 : " + testValue1);
System.out.println( "Thread 2 testValue : " + testValue);
}
}
}
public class VolatileExample {
public static void main(String args[]) {
new ExampleThread("Thread 1 ").start();
new ExampleThread("Thread 2 ").start();
}
}
output:
Thread 1 testValue1 : 10
Thread 1 testValue : 10
Thread 2 testValue1 : 0
Thread 2 testValue : 0