Pre-record
The previous review is java5 in the thread pool knowledge, this time is to review with the return value of the callable and future knowledge.
Scenarios and codes
Since Futuretask implements two interfaces, runnable and future, it can either be executed as a runnable thread, or it can be a return value callable for the future, so what are the benefits 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.
The first type of application
Waiting for the result, the program is not able to do other operations, and directly to call a method to get the results of the return feel is the same effect.
Public class callableandfuture { /** * @param args * * Public Static void Main(string[] args) {Executorservice ThreadPool = Executors.newsinglethreadexecutor (); future<string> future = Threadpool.submit (NewCallable<string> () { PublicStringPager()throwsException {Thread.Sleep ( -);return "Test"; }; } ); System.out.println ("Wait for the result ...");Try{System.out.println ("Results---->"+future.get ()); }Catch(Interruptedexception e) {E.printstacktrace (); }Catch(Executionexception e) {E.printstacktrace (); } }}
The second type of application
Completionservice submits a set of callable tasks at a time, it take method returns the future object corresponding to a callable task that has already been completed.
Example: Like a fisherman in the sea cast a net, sprinkle a lot of areas to wait for the net, the specific order of the net is which net into the fish is the first to accept which.
Public classcallableandfuture {Executorservice threadpooltest = Executors.newfixedthreadpool (Ten); Completionservice<integer> Completionservice =NewExecutorcompletionservice<integer> (threadpooltest);//Submit 10 Quests for(inti =0; I <Ten; i++) {Finalintindex = i; Completionservice.submit (NewCallable<integer> () {@Override PublicIntegerPager() throws Exception {Thread.Sleep (NewRandom (). Nextint ( the));returnIndex } }); } for(inti =0; I <Ten; i++) {System. out. println (Completionservice.take ().Get()); } }}
Above.....
Ten: Callable and future