3

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

2 回答 2

2

您没有按照Executor预期的方式使用 s 。它们应该是长期存在的,在应用程序启动时创建并在最后拆除。不要在正常处理过程中使用shutdownNow和。awaitTermination

如果您想等待任务的结果,请调用提交时返回get()的那个。Future

于 2012-11-05T13:47:17.673 回答
1

我会使用 ScheduledExecutorService 在 5 秒后自行关闭。

于 2012-11-05T08:36:23.093 回答