java - ScheduledExecutorService 执行与它下面的其他代码并行运行
问题描述
我是第一次使用 ScheduledExecutorService,但无法理解它的行为。我编写了一个简单的代码并假设它按顺序执行,但事实并非如此。
public static void main(String[] args) throws InterruptedException {
AtomicInteger runTimeCounter = new AtomicInteger(1);
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
int totalCountToRun = 4;
int threadSleepTime = 5;
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (runTimeCounter.get() <= totalCountToRun) {
try {
SimpleDateFormat formatter= new SimpleDateFormat("HH:mm:ss z");
Date date = new Date(System.currentTimeMillis());
String time = formatter.format(date);
//create threaddump files in temp location
System.out.println("from task "+time);
//Increment the counter
runTimeCounter.getAndIncrement();
} catch (Exception ex) {
}
} else {
executorService.shutdown();
}
}
}, 5, threadSleepTime, TimeUnit.SECONDS);
for(int i=1;i<=4;i++ ){
SimpleDateFormat formatter= new SimpleDateFormat("HH:mm:ss z");
Date date = new Date(System.currentTimeMillis());
String time = formatter.format(date);
//create threaddump files in temp location
System.out.println("from for "+time);
Thread.sleep(5000);
}
}
它打印:
from for 22:17:27 IST
from task 22:17:27 IST
from task 22:17:32 IST
from for 22:17:32 IST
from task 22:17:37 IST
from for 22:17:37 IST
from task 22:17:42 IST
from for 22:17:42 IST
有人可以指导我这里到底发生了什么以及如何按顺序运行代码。
解决方案
推荐阅读
- c++ - 处理参数包时何时需要省略号?
- grails3 - 可以在 Tomcat 10 上部署 Grails 3 服务器吗?
- azure-data-factory - CA 证书身份验证:带有 Anaplan 的 Azure 数据工厂
- playwright - 剧作家不显示警报消息
- javascript - 将 jsxbin 转换为 jsx
- excel - 从两个不同的工作表中获取值,然后复制到另一个工作表
- javascript - REACT API 调用和 NODE.JS 代理服务器错误:无法加载资源:net::ERR_CONNECTION_REFUSED
- javascript - 如何使缩放逻辑与 d3 之类的 Web 缩放事件反应原生事件?
- ruby-on-rails - 在模型集合上急切加载移动翻译
- unity3d - Unity 项目已擦除,但文件夹仍处于层次结构中