java volatile关键字使用场景

最轻量的同步

volatile 关键字通常使用在一次写,多次读的场景,使线程之间可以实时拿到更新的结果,但多次写却不能保证实时拿到

package test;

public class ThreadJoinTest {

    private static class Count extends Thread{
        private ThreadJoinTest simplOper;
        
        Object obj = new Object();
        
        public Count(ThreadJoinTest simplOper){
            this.simplOper = simplOper;
        }
         
        @Override
        public  void run() { 
                for (int i = 0; i < 10000; i++) {
                     simplOper.add1();    
                } 
        }
    }
    
    volatile int count =0;
            
     
    
     
    
    public static void main(String[] args) {
        ThreadJoinTest tjt =new ThreadJoinTest();
        Count c1= new Count(tjt);
        Count c2= new Count(tjt);
        
        c1.start();
        c2.start();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(tjt.count);
    } 
}
 

猜你喜欢

转载自blog.csdn.net/dzh145/article/details/89531802