Implement the Callable interface. The Return Value of the callable thread.
Callable
1. A return value can be provided after the task ends.
2. The call method can throw an exception.
3. Run callable to get a Future object. The Future object indicates the result of asynchronous calculation. It provides a method to check whether the calculation is complete.
Implement the Callable Interface
public class Main implements Callable{ int i; @Override public Object call() throws Exception { String str=null; for (i=0;i<100;i++){ str=Thread.currentThread().getName()+"--"+i; System.out.println(str); } return str; }}
Test
public class Client { public static void main(String[] args) { ExecutorService threadPool= Executors.newSingleThreadExecutor(); Future<String> future=threadPool.submit(new Main()); System.out.println("----------"); try { System.out.println(future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }}
After the thread ends, the future. get () method returns the result