在thread.start()和run方法之间被调用发生了什么?需要几十毫秒

时间:2019-04-28 15:18:19

标签: java multithreading jvm

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池= Executors.newFixedThreadPool(1);”和“ start = 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的评论,我发现只有在这两段代码一个接一个的情况下才会发生。但是为什么第一个总是慢?

0 个答案:

没有答案