volatile

package thread.key;

public class TestOne {

    private  volatile boolean bChange;
    
    public  static void main(String[] args) {

        /**
         * 
         * ---------  volatile
         * volatile是一种轻量级的同步,相对 synchronized开销小
         * 所谓可见性,是指当一条线程修改了共享变量的值,新值对于其他线程来说是可以立即得知的。
         * 
         * 
         * 1)写一个volatile变量时,JMM会将本地内存的变量强制刷新到主内存中去
         * 2)会使其他内存中的值无效
         * 
         * 
         * 
         * 
         * final
         * 
         * 
         * 原子性
         * 
         * 
         */
        
        try {
            TestOne testOne =  new TestOne();
            new Thread(){
                public void run() {
                    for(;;){
//                        System.out.println(Thread.currentThread()); 
                        testOne.changeStatus();
                        testOne.print(Thread.currentThread().toString());
                    }
                };
            }.start();
            Thread.sleep(1); 
            new Thread(){
                public void run() {
                    for(;;){
//                        System.out.println(Thread.currentThread()); 
//                    TestOne testOne =  new TestOne();
//                    testOne.changeStatus();
                        testOne.print(Thread.currentThread().toString());
                    }
                };
            }.start();
            
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
    
    
    public void changeStatus(){
        bChange = true;
    }
    
    public void print(String str){
        
        if (bChange) {
            System.out.println("-----"+str); 
        }else {
            System.out.println(str);
        }
    }

}

 

posted @ 2018-02-26 18:39  aLa神灯  阅读(118)  评论(0编辑  收藏  举报