JavaFX - 等待任务完成

JavaFX - 等待任务完成

问题描述:

我有一个JavaFX应用程序,它实例化几个Task对象。JavaFX - 等待任务完成

当前,我的实现(请参见下文)调用在Task对象下执行计算的行为runFactory()。与此并行,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(); 
} 

使用时您需要使用setOnSucceeded任务和可能setOnFailed建立在你的程序中的逻辑流,我建议你也让runFactory()回报的任务,而不是运行它:

// Implementation of Knuth-Morris-Pratt given a list of words and a sub-string. 
public class KnuthMorrisPratt { 
    public Task<Void> runFactory() throws InterruptedException { 
     return new Task<Void>() { 

     @Override public Void call() throws InterruptedException { 
     for (InputSequence seq: getSequences) { 
     KnuthMorrisPratt kmp = new KnuthMorrisPratt(seq, substring); 
     kmp.align(); 

     } 
     return null; 
    } 
    }; 
} 

// High-level class to run the Knuth-Morris-Pratt algorithm. 
public class AlignmentFactory { 
    public void perform() { 
    KnuthMorrisPrattFactory factory = new KnuthMorrisPrattFactory(); 
    Task<Void> runFactoryTask = factory.runFactory(); 
    runFactoryTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() { 
     @Override 
     public void handle(WorkerStateEvent t) 
     { 
      // Code to run once runFactory() is completed **successfully** 
      nextFunction() // also invokes a Task. 
     } 
    }); 

    runFactoryTask.setOnFailed(new EventHandler<WorkerStateEvent>() { 
     @Override 
     public void handle(WorkerStateEvent t) 
     { 
      // Code to run once runFactory() **fails** 
     } 
    }); 
    new Thread(runFactoryTask).start(); 
    } 
} 
+0

Dreen,我喜欢你的逻辑......谢谢。它非常有意义。 – 2013-03-05 18:59:21

+0

该解决方案看起来很有效。也就是说,这种方法的优点是什么,而不是像'Platform.runLater(nextFunction())'这样的工作作为工厂线程中的最后一步? – Vultan 2016-05-20 22:02:23

+0

感谢百万,setOnFailed()在两天挣扎后挽救了我 – Yahya 2017-04-12 17:08:58