我有 2 个 FutureTask 对象。我的任务正在并行运行。但是,我想要的是,只要其中一个 FutureTask 方法完成其执行/作业,另一个就应该停止。但是在方法内部(
我有 2 个 FutureTask 对象。我的任务正在并行运行。但是,我想要的是,只要其中一个 FutureTask 方法完成其执行/作业,另一个就应该停止。但是在方法(method1() /method2())中,我该如何停止呢?
public class Main {
public static void main(String[] args) {
try {
ExecutorService executor = Executors.newSingleThreadExecutor();
//task 1
Future future1 = executor.submit(new Callable() {
@Override
public Response call() throws Exception {
return method1();
}
});
//task 2
Future future2 = executor.submit(new Callable() {
@Override
public Response call() throws Exception {
return method2();
}
});
Response response1 = (Response) future1.get();
Response response2 = (Response)future2.get();
executor.shutdown();
if(response1!=null || response2.getMsg()!=null){
System.out.println(response2.getMsg());
}else{
System.out.println("error");
}
}catch (Exception ex){
ex.printStackTrace();
}
}
//first method
private static Response method1() {
Response response=new Response();
response.setMsg("test1"); // ==> this might take long time
return response;
}
//second method
private static Response method2() {
Response response=new Response();
response.setMsg("test1"); // ==> this might take long time
return response;
}
}
class Response {
String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
有人能帮助我理解这一点吗?