• 线程安全的atomic wrapper classes例子


    先参考一个例子 http://www.cnblogs.com/aigongsi/archive/2012/04/01/2429166.html#!comments

    即使只是i++,实际上也是由多个原子操作组成:read i; inc; write i,假如多个线程同时执行i++,volatile只能保证他们操作的i是同一块内存,但依然可能出现写入脏数据的情况。如果配合Java 5增加的atomic wrapper classes,对它们的increase之类的操作就不需要sychronized。 

    使用AtomicInteger,它封装了一些integer的原子操作,并使之线程安全

    package threadTest;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.atomic.AtomicInteger;
    
    
    public class AtomicIntegerTestApp1 {
        public static AtomicInteger count = new AtomicInteger(0);
    
        public static void inc() {
    
    //      count++;
            count.incrementAndGet();
        }
    
        public static void main(String[] args) throws InterruptedException {
    
            ExecutorService service= Executors.newFixedThreadPool(Integer.MAX_VALUE);
    
            for (int i = 0; i < 10000; i++) {
                service.execute(new Runnable() {
                    @Override
                    public void run() {
                        ThreadPoolTestApp1.inc();
                    }
                });
            }
    
            service.shutdown();
            //给予一个关闭时间(timeout),但是实际关闭时间应该会这个小
            service.awaitTermination(300, TimeUnit.SECONDS);
    
            System.out.println("运行结果:Counter.count=" + ThreadPoolTestApp1.count);
        }
    }

     Java中的原子操作包括:
    1)除long和double之外的基本类型的赋值操作
    2)所有引用reference的赋值操作
    3)java.concurrent.Atomic.* 包中所有类的一切操作
    count++不是原子操作,是3个原子操作组合
    1.读取主存中的count值,赋值给一个局部成员变量tmp
    2.tmp+1
    3.将tmp赋值给count

  • 相关阅读:
    CSS文字大小单位px、em、pt
    前台和后台数据传递综合总结
    关于JSON对象,以及联合数组,eval函数的使用参考
    C#整数的三种强制类型转换int、Convert.ToInt32()、int.Parse()的区别
    web.xml配置内容介绍
    Hibernate核心接口SessionFactory解释
    spring简单配置
    hibernate简单实例
    struts简单配置
    web.xml简单配置
  • 原文地址:https://www.cnblogs.com/winkey4986/p/5522804.html
Copyright © 2020-2023  润新知