查找了关于volatie在网上的用法示例,发现都是有问题的,网上的这些代码示例并未体现出volatile的所宣称的效果,
经过一上午的代码调整和测试验证,终于验证了volatile的可见性效果,如下所示。
public class Test extends Thread {
volatile int x = 0; //此处可以将volatile去除 或者 替换为 static,经过对比可看出volatile的作用
private void write() {
x = 5;
}
private void read() {
while (x != 5) {
}
if(x == 5){
System.out.println("------stoped");
}
}
public static void main(String[] args) throws Exception {
Test example = new Test();
Thread writeThread = new Thread(new Runnable() {
public void run() {
example.write();
}
});
Thread readThread = new Thread(new Runnable() {
public void run() {
example.read();
}
});
readThread.start();
TimeUnit.SECONDS.sleep(5); //记住此处一定要暂停5秒,以保证writeThread一定会在readThread中执行
System.out.println("------");
writeThread.start(); }}
经过一上午的代码调整和测试验证,终于验证了volatile的可见性效果,如下所示。
public class Test extends Thread {
volatile int x = 0; //此处可以将volatile去除 或者 替换为 static,经过对比可看出volatile的作用
private void write() {
x = 5;
}
private void read() {
while (x != 5) {
}
if(x == 5){
System.out.println("------stoped");
}
}
public static void main(String[] args) throws Exception {
Test example = new Test();
Thread writeThread = new Thread(new Runnable() {
public void run() {
example.write();
}
});
Thread readThread = new Thread(new Runnable() {
public void run() {
example.read();
}
});
readThread.start();
TimeUnit.SECONDS.sleep(5); //记住此处一定要暂停5秒,以保证writeThread一定会在readThread中执行
System.out.println("------");
writeThread.start(); }}