所以,我刚刚学习了volatile关键字,同时写了一些例子,我将在明天的一节。我编写了一个快速的程序来演示++和--操作不是原子的。
public class Q3 {
private static int count = 0;
private static class Worker1 implements Runnable{
public void run(){
for(int i = 0; i < 10000; i++)
count++; //Inner class maintains an implicit reference to its parent
}
}
private static class Worker2 implements Runnable{
public void run(){
for(int i = 0; i < 10000; i++)
count--; //Inner class maintains an implicit reference to its parent
}
}
public static void main(String[] args) throws InterruptedException {
while(true){
Thread T1 = new Thread(new Worker1());
Thread T2 = new Thread(new Worker2());
T1.start();
T2.start();
T1.join();
T2.join();
System.out.println(count);
count = 0;
Thread.sleep(500);
}
}
}
正如预期的那样,该程序的输出大致如下:
-1521
-39
0
0
0
0
0
0
但是,当我改变时:
private static int count = 0;
到
private static volatile int count = 0;
我的输出更改为:
0
3077
1
-3365
-1
-2
2144
3
0
-1
1
-2
6
1
1