JAVA multi-threaded container

1, ArrayList thread safe; CopyOnWriteArrayList thread-safe
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 thread safe; HashTable synchronize thread safe, `` `
of ConcurrentHashMap a" lock segment "thread safe;
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());
    }
    }

Guess you like

Origin blog.51cto.com/11147669/2425652