The thread.run is delayed dozens of ms. I know it depends on the os's scheduler, but the delay in Executor version is much more smaller. What the different between Thread.start() and 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()
start: 1556463160295, now: 1556463160371, delay 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);
});
start: 1556465388875, now: 1556465388882, delay 7
Swap "ExecutorService pool = Executors.newFixedThreadPool(1);" and "start = System.currentTimeMillis();" and the test it again
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);
});
start: 1556465668982, now: 1556465668983, delay 1
As per Sotirios Delimanolis's comment, I found it only happens when these two pieces of code one after the other. But why the first one alway slow?