我一直在研究一个 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
*/
}
}