美文网首页
java.util.concurrent.atomic.Atom

java.util.concurrent.atomic.Atom

作者: 奋斗的韭菜汪 | 来源:发表于2020-06-23 21:39 被阅读0次

    AtomicInteger (保证多线程情况下的原子操作)

    public class AtomicIntegerDemo {
        public static AtomicInteger count = new AtomicInteger(0);
    
        public static void inc(){
            try{
                Thread.sleep(1); //延迟1毫秒
    
            }catch (InterruptedException e){ //catch住中断异常,防止程序中断
                e.printStackTrace();
    
            }
            count.getAndIncrement();//count值自加1
        }
    
    
        public static void main(String[] args) throws InterruptedException {
            
            final CountDownLatch latch = new CountDownLatch(100);
            for(int i=0;i<100;i++){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        AtomicIntegerDemo.inc();
                        latch.countDown();
                    }
                }).start();
            }
            latch.await();
    
            System.out.println("运行结果:"+AtomicIntegerDemo.count);
        }
    }
    

    运行结果

    运行结果:100
    
    Process finished with exit code 0
    

    相关文章

      网友评论

          本文标题:java.util.concurrent.atomic.Atom

          本文链接:https://www.haomeiwen.com/subject/pjekfktx.html