Java uses Callable and Future to return the results of thread execution
We may need to return the result of a thread execution under some special requirements. The Callable and Futrue functions provided in java 1.5 can help you achieve this! Read the code without explanation
Package cn.kge.com; import java. util. concurrent. callable; import java. util. concurrent. executionException; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. future; public class Demo2 {public static void main (String [] args) {ExecutorService threadPool = Executors. newSingleThreadExecutor (); Future
Future = threadPool. submit (new Callable
() {Public String call () {String str = "hello"; try {Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace ();} return str + "world" ;}}); try {System. out. println ("execution result:" + future. get ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace ();}}}
Execution result: helloworld