zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    
    }
  • 相关阅读:
    HDU
    稀疏表(ST / Sparse Table)
    HDU
    HDU
    树状数组
    用 BitArray 来编写埃拉托斯特尼筛法
    BitArray 内置是逆序存储, 因此要自行实现正序输出
    位运算,位移,窗体
    按位运算,窗体程序,And,Or,Xor
    基数排序
  • 原文地址:https://www.cnblogs.com/lxh520/p/8474607.html
Copyright © 2011-2022 走看看