标签:cep 变化 inter dex 之间 col get 同步 count
①volatile关键字:保证线程之间的变量的可见性
例如:
public class RunThread extends Thread{ private boolean isRunning = true; private void setRunning(boolean isRunning){ this.isRunning = isRunning; } public void run(){ System.out.println("进入run方法.."); while(isRunning == true){ //.. } System.out.println("线程停止"); } public static void main(String[] args) throws InterruptedException { RunThread rt = new RunThread(); rt.start(); Thread.sleep(1000); rt.setRunning(false); System.out.println("isRunning的值已经被设置了false"); } }
打印结果如下:线程感受不到isRunning变量的变化(即对主线程的变量改变不可见)一直在while循环中,不会停止
将代码修改如下:将isRunning属性用volatile修饰
private volatile boolean isRunning = true;
打印结果如下:
②volatile关键字并不能保证原子性(不能保证线程安全)
例如:
public class VolatileNoAtomic extends Thread{ private static volatile int count; private static void addCount(){ for (int i = 0; i < 1000; i++) { count++ ; } System.out.println(count); } public void run(){ addCount(); } public static void main(String[] args) { VolatileNoAtomic[] arr = new VolatileNoAtomic[100]; for (int i = 0; i < 10; i++) { arr[i] = new VolatileNoAtomic(); } for (int i = 0; i < 10; i++) { arr[i].start(); } } }
打印结果:如果打印总数为10000,才能说明满足原子性,可是结果却并不是10000
由此可见,volatile并没有满足原子性
线程安全同步包括两点:互斥和可见性
volatile实现了可见性,但是不能实现互斥,要想两者都实现,得用synchronize关键字
如果要想用volatile关键字实现线程安全,就必须另外实现原子性,这时可以拥一些jdk提供的原子类:AtomicInteger等
修改上面代码如下:
public class VolatileNoAtomic extends Thread{ //private static volatile int count; private static AtomicInteger count = new AtomicInteger(0); private static void addCount(){ for (int i = 0; i < 1000; i++) { //count++ ; count.incrementAndGet(); } System.out.println(count); } public void run(){ addCount(); } public static void main(String[] args) { VolatileNoAtomic[] arr = new VolatileNoAtomic[100]; for (int i = 0; i < 10; i++) { arr[i] = new VolatileNoAtomic(); } for (int i = 0; i < 10; i++) { arr[i].start(); } } }
打印结果如下:
标签:cep 变化 inter dex 之间 col get 同步 count
原文地址:http://www.cnblogs.com/cowboys/p/7610740.html