new Thread的弊端:
- 每次new Thread新建对象性能差。
- 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机。
- 缺乏更多功能,如定时执行、定期执行、线程中断。
Executors 优势:
- 重用存在的线程,减少对象创建、消亡的开销,性能佳。
- 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。
- 提供定时执行、定期执行、单线程、并发数控制等功能。
public static void main(String[] args) throws InterruptedException {
Map<String, String> map = new ConcurrentHashMap<>();
ExecutorService service = Executors.newFixedThreadPool(100);
long start = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
CountDownLatch countDownLatch = new CountDownLatch(100);
for (int i = 0; i < 100; i++) {
service.execute(() -> {
for (int j = 0; j < 10000; j++) {
map.put(
"key" + UUID.randomUUID().toString(),
"value" + UUID.randomUUID().toString());
}
countDownLatch.countDown();
}
);
}
countDownLatch.await();
service.shutdown();
long end = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
System.out.println(end - start + "毫秒");
System.out.println(map.size());
}