java Executor学习与理解

本文通过对比使用 Java Executor 服务和直接创建线程的方式执行大量任务,来评估 Java Executor 服务的性能表现。测试中设置了不同的线程池大小,并记录了任务全部完成所需的时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java Executor

未完待续

package abc.repeat.test;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ExecutorTest {

    public static void main(String[] args) throws IOException, InterruptedException {
        boolean useExecutor = false;
        int waitMillis = 1000;
        int taskNo = 10000;

        long startTime = System.currentTimeMillis();

        if (useExecutor) {
            ExecutorService service = Executors.newFixedThreadPool(1);
            //ExecutorService service = Executors.newFixedThreadPool(10);
            //ExecutorService service = Executors.newFixedThreadPool(100);
            for (int i = 0; i < taskNo; i++) {
                Runnable run = new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("thread start");
                    }
                };
                service.execute(run);
            }
            service.shutdown();
            service.awaitTermination(waitMillis, TimeUnit.MILLISECONDS);

        } else {
            for (int i = 0; i < taskNo; i++) {
                Runnable run = new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("thread start");
                    }
                };
                Thread t = new Thread(run);
                t.start();
                t.join(waitMillis);
            }
        }

        System.out.println("all thread complete");
        long endTime = System.currentTimeMillis();
        System.out.println(String.format("TimeElapse: %s", endTime - startTime));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值