我有一个 JavaFX 应用程序,它实例化了几个Task对象。
目前,我的实现(见下文)调用行为runFactory()在 Task 对象下执行计算。与此并行,调用nextFunction()。有没有办法让nextFunction() “等待”直到前一个任务完成?
我理解thread.join()一直等到正在运行的线程完成,但是对于 GUI,由于事件调度线程,还有额外的复杂层。事实上,将thread.join()添加到下面代码段的末尾只会停止 UI 交互。
如果有任何建议如何让nextFunction等到它的前一个函数runFactory完成,我将不胜感激。
谢谢,
// High-level class to run the Knuth-Morris-Pratt algorithm.
public class AlignmentFactory {
public void perform() {
KnuthMorrisPrattFactory factory = new KnuthMorrisPrattFactory();
factory.runFactory(); // nextFunction invoked w/out runFactory finishing.
// Code to run once runFactory() is complete.
nextFunction() // also invokes a Task.
...
}
}
// Implementation of Knuth-Morris-Pratt given a list of words and a sub-string.
public class KnuthMorrisPratt {
public void runFactory() throws InterruptedException {
Thread thread = null;
Task<Void> task = new Task<Void>() {
@Override public Void call() throws InterruptedException {
for (InputSequence seq: getSequences) {
KnuthMorrisPratt kmp = new KnuthMorrisPratt(seq, substring);
kmp.align();
}
return null;
}
};
thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}