Java Volatile
2017-06-27 本文已影响47人
奔跑的笨鸟
用volatile修饰的变量,其他线程在每次使用这个变量的时候,都会读取变量修改后的最的值。volatile变量每次修改后都会把值从线程本地内存刷新到主内存,读取也一样,每次都从主内存中读取。
用volatile修改的变量,如果自增减的操作,并不能保证原子性。
package cn.true123;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class VolatileTest {
private volatile int count = 0;
public void increase() {
count++;
}
CountDownLatch countDownLatch = new CountDownLatch(100);
class Increase implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100000; i++)
increase();
countDownLatch.countDown();
}
}
public int getCount(){
return count;
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
VolatileTest volatileTest = new VolatileTest();
for (int i = 0; i < 100; i++) {
Runnable runnable = volatileTest.new Increase();
executorService.execute(runnable);
}
try {
volatileTest.countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=="+volatileTest.getCount());
}
}
执行结果:
==9999615
可见volatile变量,能保证对线程可见性,不能保证原子性。