当另一个性能密集型线程正在运行时,不会触发Java ScheduledExecutorService

时间:2018-03-26 21:15:39

标签: java multithreading executorservice scheduledexecutorservice

我有一个Java应用程序,它由三个主线程组成:

  1. 处理用户输入的主线程,并启动以下线程。
  2. 计算某些东西的线程,利用70-80%的CPU。
  3. “监视”线程,应该每2秒运行一次,并从文件中读取1条短线。
  4. 我的问题是第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秒钟调用一次监听线程?

0 个答案:

没有答案