Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 1.6-从executor服务线程返回到主类_Java_Multithreading_Executorservice_Threadpoolexecutor - Fatal编程技术网

Java 1.6-从executor服务线程返回到主类

Java 1.6-从executor服务线程返回到主类,java,multithreading,executorservice,threadpoolexecutor,Java,Multithreading,Executorservice,Threadpoolexecutor,通过使用Executor服务创建3个线程(extends Runnable)并提交它们,我正在从我的主类执行三个任务。如下图所示: ExecutorService executor = Executors .newFixedThreadPool(3); A a= new A(); B b= new B(); C c= new C();

通过使用Executor服务创建3个线程(extends Runnable)并提交它们,我正在从我的主类执行三个任务。如下图所示:

    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的情况下从这些线程返回一些东西吗?

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

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

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

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

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

无论何时在中发生错误,您都会将返回值存储在MyFutureTask中,然后可以像正常FutureTask一样读取它。

而不是通过
execute
提交任务,该方法不允许您捕获
run
方法之外的异常,使用
submit
返回
Future
。然后,您可以调用
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
}
Future fa=执行人提交(a);
试一试{
fa.get();//等待未来
}捕获(执行例外){
System.out.println(“出错:+e.getCause());
//做一些具体的事情
}

使用
submit
返回
未来的
方法,而不是通过
execute
提交任务,该方法不允许您捕获
run
方法之外的异常。然后,您可以调用
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
}
Future fa=执行人提交(a);
试一试{
fa.get();//等待未来
}捕获(执行例外){
System.out.println(“出错:+e.getCause());
//做一些具体的事情
}

您可以添加
Runnable
s可以将捕获的已检查异常包装到
RuntimeException
的子类的实例中,以便重试…您可以添加
Runnable
s可以将捕获的已检查异常包装到
RuntimeException
的子类的实例中,以便重试…