码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA多线程并发容器

时间:2019-08-01 17:22:43      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:put   oid   inter   count   imp   down   asn   final   interrupt   

1、ArrayList线程不安全;CopyOnWriteArrayList线程安全
package concurrent;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Auth: zhouhongliang
 * Date:2019/8/1
 * CopyOnWriteArrayList 替代 ArrayList
 */
public class CopyOnWriteArrayListDemo {
    public static void main(String[] args) {
        List<Integer> list = new CopyOnWriteArrayList<>();
        //List<Integer> list = new CopyOnWriteArrayList<>();
        for (int i=0;i<1000;i++){
            list.add(i);
        }
        Iterator iterator = list.iterator();
        while(iterator.hasNext()){
            list.remove(iterator.next());
        }
        System.out.println(list);
    }
}

2、HashMap线程不安全;HashTable synchronize线程安全、```
ConcurrentHashMap采用”分段锁”线程安全;
package concurrent;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**

  • Auth: zhouhongliang
  • Date:2019/8/1
    */
    public class ConcurrentHashMapDemo {
    public static void main(String[] args) throws InterruptedException {
    Map map = new HashMap();//线程不安全
    //Map map = new Hashtable();//线程安全
    //Map map = new ConcurrentHashMap();//线程安全
    ExecutorService executorService = Executors.newCachedThreadPool();
    CountDownLatch countDownLatch = new CountDownLatch(10000);
    for (int i=0;i<10000;i++){
    final Integer index = i;
    executorService.execute(()->{
    map.put(index,index);
    countDownLatch.countDown();
    });
    }
    countDownLatch.await();
    System.out.println(map.size());
    }
    }

JAVA多线程并发容器

标签:put   oid   inter   count   imp   down   asn   final   interrupt   

原文地址:https://blog.51cto.com/11147669/2425652

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!