我一直在开发一个 Java GUI 应用程序,该应用程序在特定操作上执行某些任务。我一直在使用 ExecutorService 完成这项任务。现在使用多线程工作正常,但问题是我不想阻止我的 GUI。用户可能想要取消当前操作并可能请求另一个操作。但是在使用 ExecutorService 时,我的主线程被阻塞了。我想等待我的子线程完成,使用 ExecutorService 调用,同时仍然能够在 GUI 上工作。
更新后的代码是:
ExecutorService child = Executors.newCachedThreadPool();
ExecutorService es = Executors.newCachedThreadPool();
@Action
public void doAction() {
/** Some Code goes here */
if(Condition){
if(!(es.isTerminated()||es.isShutdown())){
es.shutdownNow();
es = Executors.newCachedThreadPool();
}
es.execute(new Runnable() {
public void run() {
if(!(child.isTerminated()||child.isShutdown())){
child.shutdownNow();
child = Executors.newCachedThreadPool();
}
for(loopConditions){
child.execute(new Runnable() {
public void run() {
//Perform Some Task Here
}
});
}
child.shutdown();
try {
boolean finshed = child.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException ex) {
child.shutdownNow();
Logger.getLogger(MySearchView.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("All Child Threads finished Execution");
}
});
es.shutdown();
try {
boolean finshed = es.awaitTermination(5, TimeUnit.MINUTES);
} catch (InterruptedException ex) {
es.shutdownNow();
Logger.getLogger(MySearchView.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("All Threads finished Execution");
/**
* Code that should run after all Threads finishes their Execution
*/
}
}
最佳答案
您没有按照预期的方式使用 Executor
。它们应该是长期存在的,在应用程序启动时创建并在最后被拆除。不要在正常处理期间使用 shutdownNow
和 awaitTermination
。
如果您想等待任务的结果,请在您提交任务时返回的 Future
上调用 get()
。
关于java - 等到子线程完成,但不要阻塞主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13228442/