volatile关键字是JVM提供的一种轻量级的同步机制,主要要2种作用:
即一个线程修改了公共数据,新值对于其他线程来说是可以立即得知的。
public class VolatileStopThread1 extends Thread { private boolean stop = false; public void stopMe() { stop = true; } public void run() { int i = 0; System.out.println(Thread.currentThread().getName()+ " " + System.currentTimeMillis()); while (!stop) { i++; } System.out.println(Thread.currentThread().getName()+ " "+ System.currentTimeMillis()); System.out.println("Stop thread"); } public static void main(String args[]) throws InterruptedException{ VolatileStopThread1 t = new VolatileStopThread1(); t.start(); Thread.sleep(1000); t.stopMe(); Thread.sleep(1000); } }
图1 没添加volatile的运行结果
public class VolatileStopThread2 extends Thread { private volatile boolean stop = false; public void stopMe() { stop = true; } public void run() { int i = 0; System.out.println(Thread.currentThread().getName()+ " " + System.currentTimeMillis()); while (!stop) { i++; } System.out.println(Thread.currentThread().getName()+ " "+ System.currentTimeMillis()); System.out.println("Stop thread"); } public static void main(String args[]) throws InterruptedException{ VolatileStopThread2 t = new VolatileStopThread2(); t.start(); Thread.sleep(1000); t.stopMe(); Thread.sleep(1000); } }
图2 添加volatile的运行结果
结果分析:
1)从图1中可以看出,线程Thread-0处于死循环,这是因为其每次从工作内存中获取数据,所以只能读到stop = false。
2)从图2中可以看出,线程Thread-0能够跳出循环。这是因为共享变量加了volatile关键之后,线程被强制从主内存中读取共享数据,从而保证一个线程更新的数据能够被另外一个线程读取到。
int a = 0; volatile boolean flag = false; // 线程A访问方法writer() public void writer() { a = 1; flag = true; } // 线程B访问方法writer() public void reader() { if (flag) { try { throw new Exception(); }catch(Exception e) { e.printStackTrace(); } }else{ System.out.println(a); } }
结果分析:
通过上面的伪代码可以看出,如果flag没有被volatile修饰,就可能会由于指令重排序的优化,导致writer方法中flag = tru被提前执行,从而导致线程B访问出错。
Volatile虽然能够保证共享变量在线程之间的可见性,却不具备原子性。
public classVolatileAtomicTest1 { public static volatile int race = 0; public static void increase(){ race ++; } private static final int THREADS_COUNT= 20; public static void main(String[] args) throws InterruptedException { Thread[]threads= newThread[THREADS_COUNT]; for(int i = 0; i < 10; i++){ threads[i] = new Thread(new Runnable() { @Override public void run() { for(int i = 0; i < 10000; i++){ increase(); } } }); threads[i].start(); } Thread.sleep(2000); System.out.println(race); } }
图 3 未添加synchronized的运行结果
public classVolatileAtomicTest2 { public static volatile int race = 0; public synchronized static void increase(){ race ++; } private static final int THREADS_COUNT= 20; public static void main(String[] args) throws InterruptedException { Thread[]threads= newThread[THREADS_COUNT]; for(int i = 0; i < 10; i++){ threads[i] = new Thread(new Runnable() { @Override public void run() { for(int i = 0; i < 10000; i++){ increase(); } } }); threads[i].start(); } Thread.sleep(2000); System.out.println(race); } }
图片4 添加synchronized的运行结果
结果分析:
理论上结果应该是100000,但是图3的结果却是79671。这是因为代码中race++这一行不是原子操作,是非线程安全的,其可以分为3个步骤,从主内存中读取出race的值,计算race的值和将race的值写入主内存中。假如一个线程在计算race的值,而另外一个线程也在修改race的值,这样就会出现脏读。
3.1 关键字volatile只能修饰变量,而synchronized可以修饰方法和代码块。
3.2 多线程访问volatile关键字不会发生阻塞,而synchronized会出现阻塞。
3.3 volatile关键字只能保证数据的可见性,不能保证原子性;而synchronized可以保证原子性和可见性。
随着JDK新版本的发布,synchronized关键字的性能不断提高,因此在处理并发操作时,优先选择synchronized关键字而非volatile。
