Then on a continuation of the contract and the study, this article describes the callable and future, they are very interesting, one produces results, one to get results.
The callable interface is similar to runnable, which can be seen from the name, but runnable does not return the result, and the exception that returns the result cannot be thrown, and the callable function is more powerful, and after being executed by the thread, the value can be returned. This return value can be obtained by the future, that is to say, the future can get the return value of the asynchronous execution task , here is a simple example:
1 Public classCallableandfuture {2 Public Static voidMain (string[] args) {3Callable<integer> callable =NewCallable<integer>() {4 PublicInteger Call ()throwsException {5 return NewRandom (). Nextint (100);6 }7 };8futuretask<integer> future =NewFuturetask<integer>(callable);9 NewThread (Future). Start ();Ten Try { OneThread.Sleep (5000);//might do something A System.out.println (Future.get ()); -}Catch(interruptedexception e) { - e.printstacktrace (); the}Catch(executionexception e) { - e.printstacktrace (); - } - } +}
Futuretask implements two interfaces, runnable and future, so it can be executed as a runnable thread, and can be used as the future to get callable return value , so what is the benefit of using this combination? Assuming that there is a time-consuming return value that needs to be computed, and that the return value is not immediately required, then you can use this combination to compute the return value with another thread, and the current thread can do other things before using the return value, and when this return value is needed, then the future is not beautiful! Here is an introduction to the future model: Http://openhome.cc/Gossip/DesignPattern/FuturePattern.htm.
Here's another way to use callable and the future, execute callable through the Executorservice submit method, and return to the future with the following code:
1 Public classCallableandfuture {2 Public Static voidMain (string[] args) {3Executorservice ThreadPool =executors.newsinglethreadexecutor ();4future<integer> future = Threadpool.submit (NewCallable<integer>() {5 PublicInteger Call ()throwsException {6 return NewRandom (). Nextint (100);7 }8 });9 Try {TenThread.Sleep (5000);//might do something One System.out.println (Future.get ()); A}Catch(interruptedexception e) { - e.printstacktrace (); -}Catch(executionexception e) { the e.printstacktrace (); - } - } -}
The code is not a lot simpler , Executorservice inherits from executor, its purpose is to manage thread objects for us, thus simplifying concurrent programming , executor so that we do not need to display the life cycle of managing threads, is the JDK The preferred way to start a task after 5.
Perform multiple tasks with return values and get multiple return values
public class Callableandfuture {public static void main (string[] args) {Executorservice ThreadPool = Executors.newcachedt Hreadpool (); Completionservice<integer> cs = new executorcompletionservice<integer> (threadPool); for (int i = 1; i < 5; I + +) {Final int taskID = I;cs.submit (new callable<integer> () {public Integer call () throws Exception {return TaskID;} });} Possible to do something for (int i = 1; i < 5; i++) {try {System.out.println (Cs.take (). Get ())} catch (Interruptedexception e) {E.prin Tstacktrace ();} catch (Executionexception e) {e.printstacktrace ();}}}}
In fact, you can not use Completionservice, you can first create a set of future types, with executor submitted task return value added to the collection, and finally iterate through the collection of data, code slightly.
This article from: Gao | Coder, the original address: http://blog.csdn.net/ghsau/article/details/7451464, reprint please specify.
Java Multithreading Technology (callable and future)