有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何防止执行器队列中等待空闲线程的任务

我在多个线程上有很多操作要做

应允许暂停计算和增加/减少螺纹量,然后取消暂停计算

此时,我可以增加线程数量——Future已经生成并在队列中等待的任务一直在处理,根据文档,线程不能减少:

public void setCorePoolSize(int corePoolSize)

Sets the core number of threads. This overrides any value set in the constructor. If the new value is smaller than the current value, excess existing threads will be terminated when they next become idle. If larger, new threads will, if needed, be started to execute any queued tasks.

所以我的主要问题是: 如何暂停执行器以不执行队列中等待的任务

类示例定义:

import java.util.concurrent.*;

public class Calc {

    private int numberOfThreads;
    private ThradPoolExecutor pool;
    private Future fut;

    public void setNumberOfThreads(int threads) {
        this.numberOfThreads = threads + 1;
    }

    public void start() {
        if(es == null){
            pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(numberOfThreads);
        } else {
            pool.setCorePoolSize(numberOfThreads);
            pool.setMaximumPoolSize(numberOfThreads);
        }
        fut = pool.submit(() -> {
            while (true) {
                pool.execute(this::calculate);
            }
        });
    }

    public void suspendCalculations() {
        fut.cancel(true);
    }

    public void continueCalculations() {
        start();
    }

    private void calculate() {
        // calculation logic, not important
    }
}

根据我的例子,让我们想象一下情况:

  1. 调用setNumberOfThreads(5)
  2. 呼叫开始()
  3. fut将创建一个大队列,其中包含等待处理的任务(随机数为10000)
  4. 调用suspendCalculations()
  5. 调用setNumberOfThreads(2)
  6. 调用连续计算()

这样线程就不能减少了——我们有10000个任务要在队列中处理,所以我们需要等待队列何时为空

我想等到5个线程上的5个任务结束,并且在调用continueCalculations之前,队列(10000)中的任务不会传递给线程。 通过这种方式,我可以在继续计算之前调用setCorePoolSize(2),因为由于suspendCalculations,线程将不会处理任务


共 (0) 个答案