Commit 75718739 authored by Mohamad Bashar Desoki's avatar Mohamad Bashar Desoki

InvokeAll vs InvokeAny

parent 6456a84a
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;
public class InvokeAll {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Set<Callable<String>> callables = new HashSet<Callable<String>>();
callables.add(new Callable<String>() {
public String call() throws Exception {
return Thread.currentThread().getName() + " Task 1";
}
});
callables.add(new Callable<String>() {
public String call() throws Exception {
return Thread.currentThread().getName() + " Task 2";
}
});
callables.add(new Callable<String>() {
public String call() throws Exception {
return Thread.currentThread().getName() + " Task 3";
}
});
try {
List<Future<String>> result = executorService.invokeAll(callables); //Once of task is fully executed the other waiting task will get canceled
for (Future<String> res : result) {
System.out.println(res.get());
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
executorService.shutdown();
}
}
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class InvokeAny {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Set<Callable<String>> callables = new HashSet<Callable<String>>();
callables.add(new Callable<String>() {
public String call() throws Exception {
return Thread.currentThread().getName()+" Task 1";
}
});
callables.add(new Callable<String>() {
public String call() throws Exception {
return Thread.currentThread().getName()+" Task 2";
}
});
callables.add(new Callable<String>() {
public String call() throws Exception {
return Thread.currentThread().getName()+" Task 3";
}
});
try {
String result = executorService.invokeAny(callables); //Once of task is fully executed the other waiting task will get canceled
System.out.println(result);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
executorService.shutdown();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment