We may need to return the results of a thread execution under certain special requirements, and the Java 1.5 provides callable and futrue to help you achieve it! No explanation look at the code
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.newsinglethreadexecuto R (); future<string> future = Threadpool.submit (new callable<string> () {public String call () {String str = "Hello"; try {thread.sleep;} 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
Java uses callable and future to return the results of thread execution