Use Callable<V> instead of Thread (or Runnable ) so you can get the result as Future<V> and use ExecutorService to call it.
Here is SSCCE , just copy ' paste'n'run :
package com.stackoverflow.q2413389; import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test { public static void main(String... args) throws Exception { ExecutorService executor = Executors.newCachedThreadPool(); List<Future<String>> results = executor.invokeAll(Arrays.asList(new Task())); for (Future<String> result : results) { System.out.println(result.get());
Update : according to your update with the question of how to kill it after a timeout, use ScheduledExecutorService instead. The code has changed a bit here:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); List<Future<String>> results = executor.invokeAll(Arrays.asList(new Task()), 1, TimeUnit.SECONDS);
source share