标签:代码 oid interrupt volatile chap pack 一个 ted exce
闲话少叙,上代码
package com.dwz.concurrency2.chapter3; public class VolatileTest { private static volatile int INIT_VALUE = 0; private static final int MAX_LIMIT = 5; public static void main(String[] args) { new Thread(() -> { int localValue = INIT_VALUE; while (localValue < MAX_LIMIT) { if(localValue != INIT_VALUE) { System.out.printf("The value updated to [%d]\n", INIT_VALUE); localValue = INIT_VALUE; } } }, "READER").start(); new Thread(() -> { int localValue = INIT_VALUE; while (localValue < MAX_LIMIT) { System.out.printf("update the value to [%d]\n", ++localValue); INIT_VALUE = localValue; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } }, "UPDATER").start(); } }
测试结果,出现两种情况:
1.INIT_VALUE被volatile关键字修饰时,READER线程是可以感知到UPDATER的变化
update the value to [1]
The value updated to [1]
update the value to [2]
The value updated to [2]
update the value to [3]
The value updated to [3]
update the value to [4]
The value updated to [4]
update the value to [5]
The value updated to [5]
2.INIT_VALUE缺少volatile关键字修饰时,READER线程感知不到UPDATER的变化
update the value to [1]
update the value to [2]
update the value to [3]
update the value to [4]
update the value to [5]
volatile可以保证内存可见性,有序性,不让jvm自作主张去优化,可以保证读之前的写操作完成,但是不能保证原子性
标签:代码 oid interrupt volatile chap pack 一个 ted exce
原文地址:https://www.cnblogs.com/zheaven/p/12100231.html