【问题标题】:Wait until child Thread Finishe, But Do Not Block Main Thread等到子线程完成,但不要阻塞主线程
【发布时间】:2012-11-05 08:32:57
【问题描述】:

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

【问题讨论】:

  • 使用 ExecutorService 的原因是什么(确定没有错),也许还有另一种方式,也许 ExecutorService 是正确的方式

标签: java multithreading swing executorservice


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 但我不能这么早就关闭它。该操作可能需要几秒到几分钟才能完成,如果用户不想启动新操作,它应该继续。
    • 在这种情况下,我会保存未来并在您有新操作时取消它。 if(future != null) future.cancel(true); future = es.submit(new MyNewTask());
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多