用于中断和重新启动计算的并发算法



我正在开发一个应用程序,该应用程序允许用户调整多个参数,然后执行可能需要长达一分钟的计算,之后它将结果显示给用户。

我希望用户能够调整参数并重新开始计算,从而终止当前计算的进度。

此外,从编程的角度来看,我希望能够在计算完成或中断之前阻塞,并且能够知道哪个。

在伪代码中,这大致是我正在寻找的:

method performCalculation:
    interrupt current calculation if necessary
    asynchronously perform calculation with current parameters
method performCalculationBlock:
    interrupt current calculation if necessary
    perform calculation with current parameters
    if calculation completes:
        return true
    if calculation is interrupted:
        return false

到目前为止,我所拥有的满足第一种方法,但我不确定如何修改它以添加阻止功能:

private Thread computationThread;
private Object computationLock = new Object();
private boolean pendingComputation = false;
...
public MyClass() {
    ...
    computationThread = new Thread() {
        public void run() {
            while (true) {
                synchronized (computationLock) {
                    try {
                        computationLock.wait();
                        pendingComputation = false;
                        calculate();
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
        private void checkForPending() throws InterruptedException {
            if (pendingComputation)
                throw new InterruptedException();
        }
        private void calculate() {
            ...
            checkForPending();
            ...
            checkForPending();
            ...
            // etc.
        }
    };
    computationThread.start();
}
private void requestComputation() {
    pendingComputation = true;
    synchronized (computationLock) {
        computationLock.notify();
    }
}

添加此功能的最佳方法是什么?或者有没有更好的方法来设计程序来完成所有这些事情?

如果您使用的是 JDK 5 或更早版本,请检查 java.util.concurrent 软件包。FutureTask 类似乎符合您的要求:具有阻塞功能的可取消异步计算。

最新更新