并发编程基础04-volatile关键字

版权声明:博观而约取,厚积而薄发。 https://blog.csdn.net/BruceLiu_code/article/details/87989029

1.volatile

  我们知道volatile关键字的作用是保证变量在多线程之间的可见性,它是java.util.concurrent包的核心,没有volatile就没有这么多的并发类给我们使用.
volatile关键字的主要作用是使变量在多个线程间可见
示例1:

/**
 * @author bruceliu
 * @create 2019-02-27 20:25
 */
public class RunThread extends Thread {

    private boolean isRunning = true;

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

    public void run() {
        System.out.println("进入run方法..");
        int i = 0;
        while (isRunning == true) {
            //这里是一个空的循环
        }
        System.out.println("线程停止");
    }

    public static void main(String[] args) throws InterruptedException {
        RunThread rt = new RunThread();
        rt.start();

        Thread.sleep(2000);
        rt.setRunning(false);

        System.out.println("isRunning的值已经被设置了false");
    }
}

上述例子中虽然isRunning的值已经被设置了false,但是线程还是没有停止,这是为什么呢?
  一个线程可以以执行的操作有使用(use)、赋值(assign)、装载(load)、存储(stroe)、锁定(lock)、解锁(unlock).而主内存可以执行的操作有读(read)、写(write)、锁定(lock)、解锁(unlock),每个操作都是原子性的
  volatile的作用就是强制线程到主内存(共享变量)里去读取变量,而不是去线程工作内存区中读取。从而实现了多个线程间的变量可见性,也就是满足线程安全的可见性。
在这里插入图片描述
  对于普通的共享变量来讲,线程A将其修改为某个值发生在线程A的本地内存中,此时还未同步到主内存中去;而线程B已经缓存了该变量的旧值,所以就导致了共享变量值的不一致。解决这种共享变量在多线程模型中的不可见性问题,较粗暴的方式自然就是加锁,但是此处使用synchronized或者Lock这些方式太重量级了,比较合理的方式其实就是volatile。
示例2:

/**
 * @author bruceliu
 * @create 2019-02-27 20:25
 */
public class RunThread extends Thread {

    private volatile boolean isRunning = true;

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

    public void run() {
        System.out.println("进入run方法..");
        int i = 0;
        while (isRunning == true) {
            //这里是一个空的循环
        }
        System.out.println("线程停止");
    }

    public static void main(String[] args) throws InterruptedException {
        RunThread rt = new RunThread();
        rt.start();

        Thread.sleep(2000);
        rt.setRunning(false);

        System.out.println("isRunning的值已经被设置了false");
    }
}

  上述例子中isRunning 使用volatile 关键字来修饰,是的这个变量在两个线程中可见,一个线程修改了其中的值,另外一个线程也会得到其修改之后的值。
  volatile关键字虽然拥有多个线程之间的可见性,但是却不具备同步性(也就是原子性),可以算作是一个轻量级的synchronized,性能要比synchronized强得多,不会造成阻塞(在很多的开源框架里,比如netty的底层代码就大量的使用了volatile,可见netty的性能一定非常的不错)。这里还需要注意的是,一般volatile用语只针对多个线程可见性变量的操作,并不能代替synchronized的同步功能。
示例3:

/**
 * volatile关键字不具备synchronized关键字的原子性(同步)
 * @author bruceliu
 * @create 2019-02-27 20:56
 */
public class VolatileNoAtomicDemo extends Thread{

    private static volatile int count;

    private static void addCount(){
        for (int i = 0; i < 1000; i++) {
            count++ ;
        }
        System.out.println(count);
    }

    public void run(){
        addCount();
    }

    public static void main(String[] args) {

        VolatileNoAtomicDemo[] arr = new VolatileNoAtomicDemo[10];

        for (int i = 0; i < 10; i++) {
            arr[i] = new VolatileNoAtomicDemo();
        }

        for (int i = 0; i < 10; i++) {
            arr[i].start();
        }
    }
}

运行结果:

1511
5997
4997
3999
7864
3000
2000
8864
7364
7093

可见volatile关键字并不具备synchronized关键字的原子性。
volatile关键字只具有可见性,没有原子性。要实现原子性建议使用atomic类的系列对象,支持原子性操作(注意atomic类只保证本身方法的原子性,并不保证多次操作的原子性)。
示例4:


/**
 * @author bruceliu
 * @create 2019-02-27 20:56
 */
public class VolatileNoAtomicDemo extends Thread{

    private static AtomicInteger count = new AtomicInteger(0);

    private static void addCount(){
        for (int i = 0; i < 1000; i++) {
            count.incrementAndGet();
        }
        System.out.println(count);
    }

    public void run(){
        addCount();
    }

    public static void main(String[] args) {

        VolatileNoAtomicDemo[] arr = new VolatileNoAtomicDemo[10];
        for (int i = 0; i < 10; i++) {
            arr[i] = new VolatileNoAtomicDemo();
        }

        for (int i = 0; i < 10; i++) {
            arr[i].start();
        }
    }
}

运行结果:

8104
9639
10000
9125
9885
8423
9315
8109
8155
8222

示例5: 注意atomic类只保证本身方法的原子性,并不保证多次操作的原子性

/**
 * @author bruceliu
 * @create 2019-02-27 21:05
 */
public class AtomicUse {

    private static AtomicInteger count = new AtomicInteger(0);

    //多个addAndGet在一个方法内是非原子性的,需要加synchronized进行修饰,保证4个addAndGet整体原子性
    public synchronized int multiAdd() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        count.addAndGet(1);
        count.addAndGet(2);
        count.addAndGet(3);
        count.addAndGet(4); //+10
        return count.get();
    }


    public static void main(String[] args) {

        final AtomicUse au = new AtomicUse();

        List<Thread> ts = new ArrayList<Thread>();
        for (int i = 0; i < 100; i++) {
            ts.add(new Thread(new Runnable() {
                public void run() {
                    System.out.println(au.multiAdd());
                }
            }));
        }

        for (Thread t : ts) {
            t.start();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/BruceLiu_code/article/details/87989029