Java Thread series (six) volatile

Java Thread series (six) volatile

The volatile keyword has visibility, not atomicity. The main purpose is to make variables visible across multiple threads. But it does not have atomicity (synchronization), it can be regarded as a lightweight synchronized, the performance is much stronger than synchronized, and it will not cause blocking.

1. volatile visibility

public class VolatileThread extends Thread {

    //volatile修辞的变量,变量发生变化时会强制性从主线程栈中读取该变量
    private volatile boolean isRuning = true;

    public void setIsRuning(boolean isRuning) {
        this.isRuning = isRuning;
        System.out.println("变量isRuning设置成功");
    }

    public void run () {
        //主线程调制的变量isRuning生效,程序退出while语句
        while (isRuning) {
           // do ...
        }
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileThread vt = new VolatileThread();
        vt.start();
        Thread.sleep(1000);
        //主线程调制的变量isRuning在线程vt中生效,即实现了可见性
        vt.setIsRuning(false);
    }
}

Second, volatile non-atomicity

To guarantee atomicity, use the synchronized rhetoric, or use the AtomicInteger class

import java.util.concurrent.atomic.AtomicInteger;

public class VolatileNotAtomic extends Thread {

    private static volatile int count;
    //private static AtomicInteger count = new AtomicInteger(0);

    public static void addCount() {
        for (int i = 0; i < 1000; i++) {
            count++;
            //count.incrementAndGet();
        }
        System.out.println(count);
        //使用volatile关键字,最后的结果不是1000*10
        //要想保证原子性,可以使用AtomicInteger类,只保证最后的结果正确,中间可能有误
    }

    public void run () {
        addCount();
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileNotAtomic[] vna = new VolatileNotAtomic[10];
        for (int i = 0; i < 10; i++) {
            vna[i] = new VolatileNotAtomic();
        }
        for (int i = 0; i < vna.length  ; i++) {
            vna[i].start();
        }
    }
}

refer to:

  1. "Java concurrent programming: volatile keyword analysis": http://www.importnew.com/18126.html

  2. "Applicable Scenarios of Volatile": https://blog.csdn.net/vking_wang/article/details/9982709

  3. Correct Use of Volatile Variables: https://www.ibm.com/developerworks/cn/java/j-jtp06197.html


Record a little bit every day. Content may not be important, but habits are!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325366783&siteId=291194637