java基础

JAVA基础—JUC之同步容器

2018-08-08  本文已影响1人  东方舵手
线程安全并发容器

1. CopyOnWriteArrayList 写复制列表

/**
 * CopyOnWriteArrayList 写复制列表
 */
public class CopyOnWriteArrayListSample {
    public static void main(String[] args) {
        //写复制列表
        List<Integer> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 1000; i++) {
            list.add(i);
        }

        Iterator<Integer> itr = list.iterator();
        while (itr.hasNext()) {
            Integer i = itr.next();
            list.remove(i);
        }

        System.out.println(list);
    }
}

运行结果

[]

2. ConcurrentHashMap 分段锁映射

/**
 * ConcurrentHashMap 分段锁映射
 */
public class ConcurrentHashMapperSample {
    public static int users = 100; //同时模拟的并发访问用户数量
    public static int downTotal = 5000; //用户下载的真实总数
    //public static int count = 0; //计数器
    public static ConcurrentHashMap count1 = new ConcurrentHashMap(); //计数器

    public static void main(String[] args) {
        //调度器,JDK1.5后提供的concurrent包对于并发的支持
        ExecutorService executorService = Executors.newCachedThreadPool();
        //信号量,用于模拟并发的人数
        final Semaphore semaphore = new Semaphore(users);

        for (int i = 0; i < downTotal; i++) {
            final Integer index = i;
            executorService.execute(() -> {

                //通过多线程模拟N个用户并发访问下载
                try {
                    semaphore.acquire();
                    count1.put(index, index);
                    //add();
                    semaphore.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
        }

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        executorService.shutdown(); //关闭调度服务
        System.out.println("下载总数:"+ count1.size());

    }

    //线程不安全
   /* private static void add() {
        count ++;
    }*/

    //线程安全
   /* public synchronized  static void add(){
        count ++;
    }*/

}

运行结果

下载总数:5000
总结
上一篇下一篇

猜你喜欢

热点阅读