volatile浅析
volatile的意思是不稳定的、易变的,但在多线程中却跟字面意思一毛钱关系没有。作为一个变量修饰符,它主要有两个作用:一个是告诉大家,该变量是一个在多个线程之间均可见的变量;另一个是告诉java虚拟机,不要对该变量进行指令重排序优化。下面举个例子说明
/** * 测试volatile的作用 * * @author wulf * @since 2018年11月18日*/ public class VolatileTest { // 开关:是否继续执行 private boolean isContinue = false; public boolean isContinue() { return isContinue; } public void setContinue(boolean isContinue) { this.isContinue = isContinue; } public VolatileTest(boolean isContinue) { this.isContinue = isContinue; } public void doSomething() { System.out.printf("%s: I'm coming for doing something.\n", Thread.currentThread().getName()); while (isContinue) { } System.out.printf("%s: I'm finished.\n", Thread.currentThread().getName()); } public static void main(String[] args) throws InterruptedException { final VolatileTest vt = new VolatileTest(true); new Thread() { @Override public void run() { vt.doSomething(); } }.start(); Thread.sleep(1000); vt.setContinue(false); System.out.println("continue is false."); } }
死循环了,输出结果:
改下这一行:
private volatile boolean isContinue = false;
输出结果: