1. 程式人生 > >[java多執行緒]高併發List與Map

[java多執行緒]高併發List與Map

    public static List<ThreadInfo> threads = new ArrayList<>();// 執行緒不安全
    public static List<ThreadInfo> threads = Collections.synchronizedList(new ArrayList<>());// 執行緒安全
    public static List<ThreadInfo> threadCopyOnWriteArrayList = new CopyOnWriteArrayList<>();// 執行緒安全
    public static ThreadLocal<List<ThreadInfo>> threadList = new ThreadLocal<List<ThreadInfo>>();// 執行緒安全
// Vector也可以考慮?no

//    public static Map<Long, Map<String, StatsReport>> threadReportMap = new HashMap<>();// 單執行緒
    public static Map<Long, Map<String, StatsReport>> threadReportMap = new ConcurrentHashMap<>();// 多執行緒

//        ThreadUtils.threads.forEach(threadInfo -> {// 單執行緒
        ThreadUtils.threads.parallelStream().forEach(threadInfo -> {// 並行
            ...
        });

CopyOnWriteArrayList的寫操作效能較差,而多執行緒的讀操作效能較好。 而Collections.synchronizedList的寫操作效能比CopyOnWriteArrayList在多執行緒操作的情況下要好很多, 而讀操作因為是採用了synchronized關鍵字的方式,其讀操作效能並不如CopyOnWriteArrayList。