温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JAVA如何实现多线程并发容器

发布时间:2021-11-24 10:37:12 来源:亿速云 阅读:155 作者:小新 栏目:编程语言

这篇文章给大家分享的是有关JAVA如何实现多线程并发容器的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

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

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

/**
 * 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;


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如何实现多线程并发容器”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI