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

时间:2014-02-08 10:31:36

标签: java multithreading concurrency locks

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

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

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

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

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();
    }
}

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

1 个答案:

答案 0 :(得分:1)

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