Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.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 如果第一个任务失败,如何并行运行任务并等待第二个任务,否则返回并让第二个任务运行_Java_Spring_Multithreading - Fatal编程技术网

Java 如果第一个任务失败,如何并行运行任务并等待第二个任务,否则返回并让第二个任务运行

Java 如果第一个任务失败,如何并行运行任务并等待第二个任务,否则返回并让第二个任务运行,java,spring,multithreading,Java,Spring,Multithreading,我有个情况 我正在创建一个RESTAPI,它将并行执行两个任务。如果第一个任务成功执行,则无需等待第二个任务并向调用者回复200。但是如果第一个任务失败,则需要等待第二个任务,并且响应将取决于第二个任务 有人能推荐一种在java中执行此任务的最佳方法吗?如果您需要并行任务,您可以使用。 他们为您提供取消方法,如果您愿意,您可以等待结果 考虑到这项简单的任务: class MyTask implements Callable<String> { private mStr;

我有个情况

我正在创建一个RESTAPI,它将并行执行两个任务。如果第一个任务成功执行,则无需等待第二个任务并向调用者回复200。但是如果第一个任务失败,则需要等待第二个任务,并且响应将取决于第二个任务


有人能推荐一种在java中执行此任务的最佳方法吗?

如果您需要并行任务,您可以使用。 他们为您提供取消方法,如果您愿意,您可以等待结果

考虑到这项简单的任务:

class MyTask implements Callable<String> {
    private mStr;
    MyTask(String str) {
        mStr = str;
    }

    @Override
    public String call() { 
        return mStr;
    }
}
类MyTask实现可调用{
私人mStr;
MyTask(字符串str){
mStr=str;
}
@凌驾
公共字符串调用(){
返回mStr;
}
}
还有一个用法:

ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> task1 = executor.submit(new MyTask("My first parallel task"));
Future<String> task2 = executor.submit(new MyTask("My second parallel task"));

try {
   String result = task1.get();
   String result2 = task2.get();
} catch(ExecutionException ex) { 
   System.out.println("Something went wrong when executing parallel tasks :" + ex); 
}
ExecutorService executor=Executors.newFixedThreadPool(2);
Future task1=executor.submit(新的MyTask(“我的第一个并行任务”);
Future task2=executor.submit(新的MyTask(“我的第二个并行任务”);
试一试{
字符串结果=task1.get();
字符串result2=task2.get();
}catch(ExecutionException ex){
System.out.println(“执行并行任务时出错:“+ex”);
}

是否使用多线程?您能否添加相关代码部分以更好地了解情况。