Java thread (6): callable and Future

Source: Internet
Author: User

Previous Article: Java thread (V)

Next, we will continue the study of sending and distributing packets in the previous article. This article describes callable and future. They are very interesting. One produces the result and one gets the result.

The callable interface is similar to runnable. It can be seen from the name, but runnable does not return the result and cannot throw an exception in the returned result. The callable function is more powerful. After being executed by a thread, the return value can be obtained by future. That is to say, future can get the return value of the asynchronous execution task. Here is a simple example:

Public class callableandfuture {public static void main (string [] ARGs) {callable <integer> callable = new callable <integer> () {public integer call () throws exception {return new random (). nextint (100) ;}}; futuretask <integer> future = new futuretask <integer> (callable); New thread (future ). start (); try {thread. sleep (5000); // you may want to do something system. out. println (future. get ();} catch (interruptedexception e) {e. printstacktrace ();} catch (executionexception e) {e. printstacktrace ();}}}

Futuretask implements two interfaces: runnable and future. Therefore, it can be executed by threads as runnable and the return value of callable as future. What are the advantages of this combination? Assume that a very time-consuming return value needs to be calculated, and this return value is not immediately required, you can use this combination and use another thread to calculate the return value, the current thread can perform other operations before using the returned value. When this return value is required, it can be obtained through future! Here is an introduction to the future mode: http://caterpillar.onlyfun.net/gossip/designpattern/futurepattern.htm.

The following shows another way to use callable and future, executorservice's submit method to execute callable and return future. The Code is as follows:

Public class callableandfuture {public static void main (string [] ARGs) {executorservice threadpool = executors. newsinglethreadexecutor (); Future <integer> future = threadpool. submit (New callable <integer> () {public integer call () throws exception {return new random (). nextint (100) ;}}); try {thread. sleep (5000); // you may want to do something system. out. println (future. get ();} catch (interruptedexception e) {e. printstacktrace ();} catch (executionexception e) {e. printstacktrace ();}}}

The code is much simpler. executorservice inherits from Executor. It aims to manage thread objects for us, so as to simplify concurrent programming. executor allows us to manage thread lifecycles without displaying them, is the preferred method for starting a task after JDK 5.

Execute multiple tasks with return values and obtain multiple return values. The Code is as follows:

Public class callableandfuture {public static void main (string [] ARGs) {executorservice threadpool = executors. newcachedthreadpool (); 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 ;}}) ;}// some things may be done for (INT I = 1; I <5; I ++) {try {system. out. println (CS. take (). get ();} catch (interruptedexception e) {e. printstacktrace ();} catch (executionexception e) {e. printstacktrace ();}}}}

In fact, you can also create a future type set without using completionservice. You can add the returned values of tasks submitted by Executor to the set, and finally conveniently retrieve data from the set. The code is omitted.
Next article: Java thread (7)

This article is from: Gao Shuang | coder, original address: http://blog.csdn.net/ghsau/article/details/7451464.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.