Reputation: 747
I have 2 FutureTask Objects. My tasks are running parallelly. However, What I want is that as soon as one of the FutureTask method completes its execution/job the other should stop. But inside method(method1() /method2()) how can I stop that?
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;
}
}
Can anyone help me to understand this?
Upvotes: 0
Views: 41