Java with a new thread that returns results: Callable__java

Source: Internet
Author: User

Java concurrent Programming: Callable, Future, and Futuretask

In the previous article we described 2 ways to create threads, one of which is to inherit thread directly, and the other is to implement the Runnable interface.

One flaw in all 2 ways is that the execution results cannot be obtained after the task has been completed.

If you need to get execution results, you must do so by sharing variables or by using thread communication, which can be cumbersome to use.

And since Java 1.5, callable and future have been provided to achieve the results of task execution after the completion of the task.

Today we'll discuss how to use the three classes callable, future and Futuretask. The following is a table of contents outline for this article:

I. Callable and runnable

Two. Future

Three. Futuretask

Four. Using the example

If there are any mistakes please forgive and welcome to criticize.

Please respect the results of the work of the author, reproduced please indicate the original link:

Http://www.cnblogs.com/dolphin0520/p/3949310.html

   I. Callable and runnable

First of all, java.lang.Runnable, it is an interface, in which only a run () method is declared:

1 2 3 Public interface Runnable {public abstract void run ();}

Because the run () method returns a value of type void, no results can be returned after the task finishes.

Callable, which is located under the Java.util.concurrent package, is also an interface in which only one method is declared, except that this method is called call ():

1 2 3 4 5 6 7 8 9 Public interface Callable<v> {/** * computes-a result, or throws a exception if unable to does so. &

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.