newFixedThreadPool简单使用

 new Thread的弊端:

  1.  每次new Thread新建对象性能差。
  2.  线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机。
  3.  缺乏更多功能,如定时执行、定期执行、线程中断。

Executors 优势:

  1. 重用存在的线程,减少对象创建、消亡的开销,性能佳。
  2. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。
  3. 提供定时执行、定期执行、单线程、并发数控制等功能。
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());

    }

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值