public class testVolatile {
private int i = 0;
// a线程调用
public void foo1() {
try {
while (true) {
Thread.sleep(10);
System.out.println("第一个:" + i);
i++;
}
} catch (InterruptedException e) {
// not to do;
}
}
// b线程调用
public void foo2() {
try {
while (true) {
Thread.sleep(10);
System.out.println("第二个:" + i);
}
} catch (InterruptedException e) {
// not to do;
}
}
public static void main(String[] args) {
final testVolatile test = new testVolatile();
// 线程1
new Thread() {
public void run() {
test.foo1();
}
}.start();
// 线程2
new Thread() {
public void run() {
test.foo2();
}
}.start();
}
}
输出结果如下:
第一个:0
第二个:1
第一个:1
第二个:2
第一个:2
第二个:3
第一个:3
第二个:4
第一个:4
第二个:5
第一个:5
第二个:6
第一个:6
第二个:7
第一个:7
第二个:8
第一个:8
第二个:9
第一个:9
第二个:10
第一个:10
变量i增加volatile 关键字后如下
第二个:0
第一个:0
第二个:1
第一个:1
第二个:2
第一个:2
第二个:3
第一个:3
第二个:4
第一个:4
第二个:5
第一个:5
第二个:6
第一个:6
第二个:7
第一个:7
第二个:8
第一个:8
第二个:9
第一个:9
第二个:10
求高人指点,变量 i 没有增加 volatile 关键字时,第二个输出为什么会随着第一个i 的变化而变化?