volatile 关键字的两层语义

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

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

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

注意:不具备原子性,使用也有很多限制,需要原子性则可以使用juc的锁机制,如:synchronized,lock,AtomicBoolean等

volatitle经典案例:

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

猜你喜欢

转载自blog.51cto.com/simplelife/2409213