package com.my;
class MultiThreadingExample implements Runnable {
private volatile int testValue;
public void run() {
for (int i = 0; i < 5; i++) {
try {
System.out.println(Thread.currentThread().getName() + ": " + i);
if (Thread.currentThread().getName().equalsIgnoreCase("T1")) {
testValue = 10+i;
}
if (Thread.currentThread().getName().equalsIgnoreCase("T2")) {
System.out.println("Test value: " + testValue);
}
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class VolatileExample {
/**
* @param args
*/
public static void main(String[] args) {
MultiThreadingExample volatileExample = new MultiThreadingExample();
Thread t1 = new Thread(volatileExample, "T1");
Thread t2 = new Thread(volatileExample, "T2");
t1.start();
t2.start();
}
}
未使用volatile修饰testValue后的运行结果:
T1: 0
T2: 0
Test value: 10
T1: 1
T2: 1
Test value: 11
T2: 2
T1: 2
Test value: 11
T2: 3
Test value: 12
T1: 3
T2: 4
T1: 4
Test value: 13
由于testValue的值保存在缓存(CPU的寄存器)中,导致线程2读取的值与线程1写入的值不同,从而产生红色部分所示的错误。使用了volatile修饰testValue值后,
程序运行结果就是正确的了
T1: 0
T2: 0
Test value: 10
T1: 1
T2: 1
Test value: 11
T1: 2
T2: 2
Test value: 12
T1: 3
T2: 3
Test value: 13
T1: 4
T2: 4
Test value: 14