Java线程类测试

对java中的线程安全类及不安全的类进行测试~

  • 线程不安全类
    • StringBuilder -> StringBuffer
    • SimpleDateFormat -> JodaTime
  • 同步容器
    • ArrayList -> Vector,Stack
    • HashMap -> HashTable(key, value不能为null)
    • Collections.synchronizedXXX(List, Set, Map)
  • 并发容器
    • ArrayList -> CopyOnWriteArrayList
    • HashSet,TreeSet -> CopyOnWriteArraySet,ConcurrentSkipListSet
    • HashMap,TreeMap -> ConcurrentHashMap,ConcurrentSkipListMap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//可以自行进行测试
public class ConcurrencyTest {

//请求总数
public static int clientTotal = 5000;
//同时并发执行的线程数
public static int threadTotal = 200;
public static int count = 0;

public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal; i++) {
executorService.execute(() -> {
try{
semaphore.acquire();
add();
semaphore.release();
} catch (Exception e){
log.error("exception" , e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("count:{}" , count);

}

private static void add(){
count++;
}
}