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);
        }
    }

}
相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息