【问题标题】:Java 1.6 - Return to the Main class from an executor service threadJava 1.6 - 从执行器服务线程返回主类
【发布时间】:2015-04-16 14:06:06
【问题描述】:

我通过使用 Executor Service 创建 3 个线程(扩展 Runnable)并提交它们来执行 Main 类中的三个任务。如下:

    ExecutorService executor = Executors
                        .newFixedThreadPool(3);

                A a= new A();
                B b= new B();
                C c= new C();

                /**
                 * Submit/Execute the jobs
                 */
                executor.execute(a);
                executor.execute(b);
                executor.execute(c);
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    //handle - show info
                    executor.shutdownNow();
                }

当线程中发生异常时,我会捕获它并执行 System.exit(-1)。但是,如果发生任何异常,我需要返回主类并在那里执行一些语句。这该怎么做?我们可以在没有 FutureTask 的情况下从这些线程返回一些东西吗?

【问题讨论】:

    标签: java multithreading executorservice threadpoolexecutor


    【解决方案1】:

    不要通过execute 提交任务,因为run 方法之外没有任何捕捉异常的能力,而是使用返回Future<?>submit。然后,您可以调用get,如果出现问题,它可能会返回ExecutionException

    Future<?> fa = executor.submit(a);
    try {
        fa.get();  // wait on the future
    } catch(ExecutionException e) {
        System.out.println("Something went wrong: " + e.getCause());
        // do something specific
    }
    

    【讨论】:

    • 您可以添加Runnables 可以将捕获的已检查异常包装到RuntimeException 子类的实例中以便重新抛出......
    【解决方案2】:

    您可以实现自己的“FutureTask”类并将其作为参数提供给 A 的构造函数:

    MyFutureTask futureA = new MyFutureTask();
    A a = new A(futureA);
    

    每当 A 中发生错误时,您将返回值存储在 MyFutureTask 中,然后可以像使用普通 FutureTask 一样读取它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-29
      • 2019-12-13
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 2014-07-18
      • 2017-05-13
      • 2019-08-18
      相关资源
      最近更新 更多