我有一个Java应用程序,它由三个主线程组成:
我的问题是第3个线程运行不正常。它在第二次执行的同时开始执行,但同时被暂停,并且仅在第二个线程完成后才恢复。
我正在使用ExecutorService
作为第二个线程,ScheduledExecutorService
作为监控线程。这是我的代码:
ExecutorService executorService = Executors.newSingleThreadExecutor();
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
public void startThreads() {
startMonitorThread();
startCPUIntensiveThread();
}
public void startMonitorThread() {
System.out.println("### Monitor started");
Runnable monitor = () -> {
readFileContent()
System.out.println("hello from monitor");
};
// run the monitor in every 2s
scheduledExecutorService.scheduleAtFixedRate(monitor, 0, 2, TimeUnit.SECONDS);
System.out.println("### Monitor scheduled");
}
public void startCPUIntensiveThread() {
Runnable runBenchmark = () -> {
try {
MyBenchmarkRunner.runBenchmark(); // runs 5 iterations, each takes 4 seconds
} catch (Exception e) {
System.err.println("Benchmark failed. See the log for more details.");
}
};
executorService.submit(runBenchmark);
}
输出:
### Monitor started
### Monitor scheduled
hello from monitor // monitor scheduled and executed
===== Running benchmark iteration 1 =====
===== Running benchmark iteration 2 =====
===== Running benchmark iteration 3 =====
===== Running benchmark iteration 4 =====
===== Running benchmark iteration 5 ===== // at least 20 seconds passed
hello from monitor // monitor executed again, but it should have been executed 2x during each benchmark iteration
hello from monitor
我应该如何修改代码以确保每2秒钟调用一次监听线程?