平时中我们使用的很多类都是线程不安全的,那么下面给出线程不安全的类及其对应的同步容器。
同步容器只是加了锁,并不代表并发安全,一般项目不推荐使用。
ArrayList------------------------->Vector, Stack
HashMap------------------------>HashTable
Collections.syncronizedXXX(List, Set, Map)
Collections.syncronizedXXX的实现方法如下:
package concurrency.example.syncContainer; import concurrency.annotations.ThreadSafe; import lombok.extern.slf4j.Slf4j; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; /* *Created by William on 2018/5/1 0001 */ @Slf4j @ThreadSafe public class ListSafeCollectionsSync { public static int clientTotal = 5000; public static int threadTotal = 200; private static List<Integer> arrayList = Collections.synchronizedList(new ArrayList<>()); public static void main(String[] args) throws InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); Semaphore semaphore = new Semaphore(threadTotal); CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0; i < clientTotal; i++) { final int finalI = i; executorService.execute(new Runnable() { @Override public void run() { try { semaphore.acquire(); update(finalI); semaphore.release(); } catch (Exception e) { log.error("Exception", e); } countDownLatch.countDown(); } }); } countDownLatch.await(); executorService.shutdown(); log.info("size:{}",arrayList.size()); } public static void update(int i) { arrayList.add(i); }
输出结果为5000,线程安全。