首页 > 解决方案 > thread.start() 和调用 run 方法之间发生了什么?需要几十毫秒

问题描述

thread.run 延迟了几十毫秒。我知道这取决于操作系统的调度程序,但 Executor 版本的延迟要小得多。Thread.start() 和 Executor.execute() 有什么不同。

        final long start = System.currentTimeMillis();
        Thread thr = new Thread(() -> {
            long now = System.currentTimeMillis();
            System.out.printf("start: %d, now: %d, delay %d \n", start, now, now - start);
        });
        thr.start()

开始:1556463160295,现在:1556463160371,延迟76

        final long start = System.currentTimeMillis();
        ExecutorService pool = Executors.newFixedThreadPool(1);
        pool.execute(() ->{
            long now = System.currentTimeMillis();
            System.out.printf("start: %d, now: %d, delay %d \n", start, now, now - start);
        });

开始:1556465388875,现在:1556465388882,延迟7

交换“ExecutorService pool = Executors.newFixedThreadPool(1);” 和“开始 = System.currentTimeMillis();” 并再次测试

        ExecutorService pool = Executors.newFixedThreadPool(1);
        final long start = System.currentTimeMillis();
        pool.execute(() ->{
            long now = System.currentTimeMillis();
            System.out.printf("start: %d, now: %d, delay %d \n", start, now, now - start);
        });

开始:1556465668982,现在:1556465668983,延迟1

根据 Sotirios Delimanolis 的评论,我发现只有当这两段代码一个接一个时才会发生。但是为什么第一个总是很慢?

标签: javamultithreadingjvm

解决方案


推荐阅读