学习java线程的相关知识
在学习java线程的相关知识的时候,输入下面的这段程序,发现,第一个线程没有在cache里面取数据,而是取了第二个线程写到主存当中的数据了 ?
为什么呢? 我这里就是想要试验volatile关键字的.
private static int INIT_VALUE = 0;
private final static int MAX_LIMIT = 50;
public static void main(String[] args) {
new Thread(){
public void run(){
int localValue = INIT_VALUE;
while (localValue < MAX_LIMIT) {
if (localValue != INIT_VALUE) {
System.out.println("The value updated to" + INIT_VALUE);
localValue = INIT_VALUE;
}
}
}
}.start();
new Thread(){
public void run (){
int localValue = INIT_VALUE;
while (INIT_VALUE < MAX_LIMIT) {
++localValue;
System.out.println("Update the value to " + localValue);
INIT_VALUE = localValue;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
输出结果如下:
Update the value to 1
The value updated to1
Update the value to 2
The value updated to2
Update the value to 3
The value updated to3
Update the value to 4
The value updated to4
Update the value to 5
The value updated to5
Update the value to 6
The value updated to6