package Threads;
/**
* Created by xfyou 2018/5/21 16:07.
*/
public class VolatileTest {
private static volatile int MY_INT = 0;
/**
* 主线程启动2个测试子线程
*
* @param args null
*/
public static void main(String[] args) {
new ChangeListener().start();
new ChangeMaker().start();
}
/**
* 此线程负责对MY_INT值改变的侦听,如果有改变就会打印出来
*/
static class ChangeListener extends Thread {
@Override
public void run() {
int local_value = MY_INT;
while (local_value < 5) {
if (local_value != MY_INT) {
System.out.println("Got Change for MY_INT : " + MY_INT);
local_value = MY_INT;
}
}
}
}
/**
* 此线程负责改变MY_INT的值
*/
static class ChangeMaker extends Thread {
@Override
public void run() {
int local_value = MY_INT;
while (MY_INT < 5) {
System.out.println("Incrementing MY_INT to " + (local_value + 1));
MY_INT = ++local_value;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
当使用volatile时,修改线程对static MY_INT值的修改,另一个侦听线程(读MY_INT的值)是可以及时读取到的,输出结果如下:
Incrementing MY_INT to 1
Got Change for MY_INT : 1
Incrementing MY_INT to 2
Got Change for MY_INT : 2
Incrementing MY_INT to 3
Got Change for MY_INT : 3
Incrementing MY_INT to 4
Got Change for MY_INT : 4
Incrementing MY_INT to 5
Got Change for MY_INT : 5
当不使用volatile时,修改线程对static MY_INT值的修改,另一个侦听线程(读MY_INT的值)可能完全读取不到(无感知),可能的输出结果如下:
Incrementing MY_INT to 1
Incrementing MY_INT to 2
Incrementing MY_INT to 3
Incrementing MY_INT to 4
Incrementing MY_INT to 5
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/15929.html