I want to execute 3 java methods and all of them return different type of data (say Class type). Is there a way I can run these 3 methods in parallel using ExecutorService
? In this way call()
method needs to return something in specific which spoils my idea of using it.
Let me know if there is a way to achieve this.
The call()
method usually returns something specific, that's why it's useful. You can create 3 different types of Callables
and there's no problem.
Callable<A> c1 = () -> { return getA(); };
Callable<B> c2 = () -> { return getB(); };
Callable<C> c3 = () -> { return getC(); };
Future<A> f1 = executor.submit(c1);
Future<B> f2 = executor.submit(c2);
Future<C> f3 = executor.submit(c3);
Executors accept Callable tasks, which are generic functional interfaces designed to return arbitrary types.
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.submit(() -> "Hello");
executorService.submit(() -> new BigDecimal("1.1"));
executorService.submit(() -> new ArrayList());
submit() returns a Future, a generic holder for the computation result, which will have the same generic type as the data returned by your Callable.
Future<String> future = executorService.submit(() -> "Hello");
To access the result, simply call get() :
String result = future.get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.