Callable, Future, and FutureTask

Source: Internet
Author: User

Callable, Future, and FutureTask
Http://www.silencedut.com/2016/06/15/Callable%E5%92%8CFuture%E3%80%81FutureTask%E7%9A%84%E4%BD%BF%E7%94%A8/

Article 4 Concurrent learning and use

In Java, the only way to enable a Thread is through the start method of the Thread and the Runnable run method executed in the Thread. Whether it is the Thread pool or the Callable, Future, or Thread pool to be introduced next, the core and most fundamental thing is to call the Thread. start ()-> Runnable. run (), the emergence of other classes can be considered to be more convenient to use Thread and Runnable, with this as the core, it is easier to understand the Java concurrency framework.

Although the Thread and Runnable classes make multi-Thread programming simple and direct, one drawback is that the execution results cannot be obtained after the task is executed. To obtain the execution result, you must share the variable or use thread communication to achieve the effect. Therefore, since Jdk1.5, a series of classes have emerged to solve these problems, such as Callable, Future, FutureTask, And the thread pool to be discussed in the next article, from usage to principle learning Java thread pool.

Since Java 1.5, Callable, Future, and FutureTask are provided, which can be used to obtain the task execution result after the task is executed.

Implementation Principle

Thread and Runnable

First, let's look at the principle of implementing multi-threaded tasks by Thread and Runnable.

The following is the simplified code for easy understanding.

1234567891011121314151617181920 Public class Thread implements Runnable {Runnable target; public Thread (Runnable runnable) {target = Runnable; // omitting tasks of other initialization threads} public void start () {nativeCreate (this, stackSize, daemon); // enable multithreading in the native method and call the run method} public void run () {if (target! = Null) {target. run ();}}}

It can be seen that target is a Runnble object. It extends Runnable through a typical decoration mode. If it is not passed in, the default value is null. You need to implement the run method to execute tasks in the new thread, otherwise, the thread will end without doing anything. So no matter how it changes, the start method of the Thread is used to open a new Thread. The run method executes the task in the newly opened Thread. Of course, the run method can also be called independently, but the thread is the caller's thread.

Typical characteristics of the modifier mode: The decorated class and the decorated class. The type remains unchanged (inheriting Runnable), and new behaviors and methods (such as start () are provided ), for details about the design mode, see the common design mode interpretation.

Callable and Future, FutureTask

First, we can see the relationship between them and Thrad and Runnable through the UML diagram:

CallableSimilar to Runnable functions, Callable has a call () function,However, the call () function has a return value.Runnable's run () function cannot return the result to the client program.

FutureCancels the execution result of the Callable task, checks whether the query is complete, obtains the result, and sets the result. The get () method is used to obtain the call () result of Callable.

FutureTaskIs the specific implementation class of Future. It implements get () and other methods to control Callabel behavior. Because Thread can only execute Runnable, FutureTask implements the Runnable interface.

Because FutureTask needs to be executed in Thread, you need to complete the specific implementation in the run () method:

12345678910 // Simplified code. To facilitate understanding of public void run () {Callable <V> c = callable; if (c! = Null & state = NEW) {V result; result = c. call (); set (result );}}

Get () is a blocking method until the result is returned or interrupted. You can also use the get (long timeout, TimeUnit unit) method to control the maximum waiting time.

123456 Public V get () throws InterruptedException, ExecutionException {int s = state; if (s <= COMPLETING) s = awaitDone (false, 0L ); // block wait for return report (s );}

We can see that the actual task of the run method of FutureTask is completed in the call of Callable, And the implementation method of FutureTask is completed in the adapter mode.

If the constructor imports Runnable, the static function callable (Runnable task,…) of Executors is used ,...) Convert Runnable to Callable:

123456 Public static Callable callable (Runnable task, T result) {if (task = null) throw new NullPointerException (); return new RunnableAdapter (task, result );}

Typical features of the adapter mode: encapsulate another object (wrapped with Callable) and provide different interfaces (Runnable interface)

Callable and Future, FutureTaskIt is often confusing to remember. After understanding it, you will know that Future and FutureTask are used to package Callable into a Runnable so that they can be executed in the Thread and provide the function of returning results, the three classes always appear at the same time. The overall understanding is a Runnable that can get the returned results.

Use

So how to use these classes? Because FutureTask implements Runnable, it can be directly executed through Thread packaging or submitted to ExecuteService for execution. In Thread, it is like using Runnable.

More details about the thread pool will be explained in the next article

The sample code is as follows:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 /*** Created by SilenceDut on 16/7/15. **/public class FutureTest {public static void main (String [] args) {FutureTest futureTest = new FutureTest (); futureTest. useExecutor (); futureTest. useThread ();} private void useExecutor () {SumTask sumTask = new SumTask (1000); ExecutorService executor = Executors. newCachedThreadPool (); FutureTask <Integer> futureTask = new FutureTask <Integer> (sumTask); executor. submit (futureTask); executor. shutdown (); try {System. out. println (Thread. currentThread (). getName () + ": useExecutor running result" + futureTask. get ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace () ;}} private void useThread () {SumTask sumTask = new SumTask (500); FutureTask <Integer> futureTask = new FutureTask <Integer> (sumTask) {@ Override protected void done () {super. done (); try {// This is the background thread System. out. println (Thread. currentThread (). getName () + ": useThread running result" + get ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace () ;}}; Thread thread = new Thread (futureTask); thread. start (); try {// This is in the main thread and will block System. out. println (Thread. currentThread (). getName () + ": useThread running result" + futureTask. get (). getName ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace () ;}} class SumTask implements Callable <Integer> {int number; public SumTask (int num) {this. number = num ;}@ Override public Integer call () throws Exception {System. out. println (Thread. currentThread (). getName (); Thread. sleep (5000); int sum = 0; for (int I = 0; I <number; I ++) {sum + = I;} return sum ;}}}

Result:

Pool-1-thread-1main: useExecutor run result 499500Thread-0main: useThread run result 124750Thread-0: useThread run result 124750

FutureTask. get () is blocked, and useExecutor () and useThread () are also blocked. Here is just a description of FutureTask. the thread where get () is located is the thread where the caller is located. If it is used in Android, it is generally get in the done method of FutureTask. At this time, get is called in the background thread, then, the UI or other threads are notified through Handler. I wrote an AysncTask alternative library asynctaskschedask to implement the specific methods of calling through the thread pool and calling by a single thread. There are specific implementation methods in it.

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.