volatile 关键字的两层语义

一旦一个共享变量(类的成员变量、类的静态成员变量)被 volatile 修饰以后,那么就具有了两层语义:

1)保证了不一样线程对这个变量进行操做时的可见性,即一个线程修改了某个变量的值,这新值对其余线程来讲是当即可见的。
(读取值时强行获取主内存中的值,设置值时将工做内存的数据刷新到主内存中)

2)禁止进行指令重排序。

注意:不具有原子性,使用也有不少限制,须要原子性则能够使用juc的锁机制,如:synchronized,lock,AtomicBoolean等

volatitle经典案例: ide

package test;

public class RunThread extends Thread {
    /** volatile */
    private /*volatile*/ boolean isRunning = true;

    private void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    public void run() {
        System.out.println(Thread.currentThread().getName()+" > start!!! 进入 run() 方法中...");
        while (isRunning) {
        }
        System.out.println(Thread.currentThread().getName()+"> stop!!! 线程结束了..."+isRunning);
    }

    public static void main(String[] args) throws InterruptedException {
        RunThread myThread = new RunThread();
        myThread.start();
        Thread.sleep(3000);
        myThread.setRunning(false);
        System.out.println(Thread.currentThread().getName()+"> isRunning 的值已经设置为了 false");
    }
}
#不加volatile结果为:
Thread-0 > start!!! 进入 run() 方法中...
main> isRunning 的值已经设置为了 false

#加volatile结果为:
Thread-0 > start!!! 进入 run() 方法中...
main> isRunning 的值已经设置为了 false
Thread-0> stop!!! 线程结束了...false
相关文章
相关标签/搜索