2017-05-17 Java并发编程学习2

volatile关键字

volatile可以保证可见性,但是不能保证原子性

volatile的一些场景:

  1. 状态标记 · public clamo’sss ServerHandler { private volatile isopen; public void run() { if (isopen) { //促销逻辑 } else { //正常逻辑 } } public void setIsopen(boolean isopen) { this.isopen = isopen } } · isopen代表是否促销,一个线程修改了isopen,其他线程都可以得到其最新值。

  2. 单例模式时懒加载保证线程安全 · class Singleton { private volatile static Singleton instance; public static Singleton getInstance() { if (instance == null) { syschronized(Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } ·

懒加载另一个比较好的方式 · public class Singleton {
static class SingletonHolder {
static Singleton instance = new Singleton();
}

public static Singleton getInstance(){  
    return SingletonHolder.instance;  
}   } ·

一个Demo: ` public class Scene {

private static int MY_INT = 0;


public static void main(String[] args) {

    new ChangeListener().start();

    new ChangeMaker().start();

}




static class ChangeListener extends Thread {
    @Override
    public void run() {
        int local_value = MY_INT;
        while ( local_value < 5){
            if( local_value!= MY_INT){
                System.out.println("Got Change for MY_INT : " + MY_INT);
                local_value= MY_INT;
            }
        }
    }
}



static class ChangeMaker extends Thread{
    @Override
    public void run() {

        int local_value = MY_INT;
        while (MY_INT <5){
            System.out.println("Incrementing MY_INT to " +  (local_value+1));
            MY_INT = ++local_value;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) { e.printStackTrace(); }
        }
    }
}

} `

Written on May 18, 2017