java - 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 的评论,我发现只有当这两段代码一个接一个时才会发生。但是为什么第一个总是很慢?
解决方案
推荐阅读
- python - 使用隐藏表单时如何克服机械化中的 ItemsNotFoundError
- ember.js - 如何对具有带有 ember 数据的纯字符串数组的对象进行建模?
- amazon-web-services - s3 跨账户策略 - 操作不适用于任何资源错误
- python - 将输入传递给函数以获取预测
- c - 如何在C中返回指向字符串数组的指针
- akka - 在 Akka HTTP 中传递请求上下文以完成是否是一种反模式?
- jquery - 无法使用 jQuery 设置选择菜单值
- dart - Flutter DataBaseException(表 category_Table 没有名为 category_id 的列)
- asp.net - 尝试在 ASP.NET 中更新数据库时出现“SQL 问题”
- java - 为什么在使用带有 JSON-B 的 Yasson 时需要来自 Glassfish 的 javax.json 作为依赖项?