Runnable is a standalone thread that performs work, but it does not return any values. If you want the thread to return a value when it is finished, you can implement the callable interface instead of the Runnable interface. The callable introduced in Java SE5 is a generic type parameter with a type parameter that represents the value returned from the method call () (instead of Run ()) and must use the Executorservice.submit () method Call it.
Thread Code:
publicclass ResulttThread implements Callable<String> { privateint id; public ResulttThread(int id) { this.id = id; } @Override public String call() throws Exception { return"The result id is " + id; }}
Calling code:
Future<String> future; ExecutorService mService = Executors.newCachedThreadPool(); for (int05; i++) { future = mService.submit(new ResulttThread(i)); System.out.println(future.get()); }
Operation Result:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Generates a return value from the thread--callable interface