Callable, Runnable, future, Futuretask

Source: Internet
Author: User

Java concurrent Programming callable, Runnable, future, Futuretask

  Java has callable, Runnable, future, futuretask these thread-related classes or interfaces, below to understand their role and differences.

I. Callable and runnable

  Similar to callable and runnable, classes that implement callable and runnable interfaces are tasks that can be run by other threads, and callable and runnable are mainly distinguished by the following:

(1) The method declared in the. Callable is call (), and the method declared in Runnable is run ().

(2). Callable the task can return a value after execution, runnable the task does not return a value after execution.

(3). The call () method can throw an exception, and the run () method cannot throw an exception.

(4). Run a callable task to get a future object.

1  Public InterfaceCallable<v> {2     /**3 * Computes a result, or throws an exception if unable to does so.4      *5      * @returncomputed result6      * @throwsException If unable to compute a result7      */8V Call ()throwsException;9 }Ten  One  A  Public InterfaceRunnable { -     /** - * When a object implementing interface <code>Runnable</code> is used the * To create a thread, starting the thread causes the object ' s - * <code>run</code> method to being called in that separately executing - * thread. - * <p> + * The general contract of the method <code>run</code> are it may - * take any action whatsoever. +      * A      * @seeJava.lang.thread#run () at      */ -      Public Abstract voidrun (); -}
Two. Future objects

The future is to cancel the execution result of the specific runnable or callable task, whether the query is complete, get the result, and set the result operation. The Get () method can be used to get the execution result, and the Get () method blocks until the task returns the result

 Public InterfaceFuture<v> {    /*** Attempts to cancel execution of this task. This attempt would * fail if the task has already completed, have already been cancelled, * or could not being Cancelle D for some and other reason. If successful, * and this task have not started when <tt>cancel</tt> was called, * this task should Neve  R run. If The task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whet     Her, the thread executing this task should is interrupted in * a attempt to stop the task. * * <p>after This method returns, subsequent calls to {@link#isDone} 'll * always return <tt>true</tt>. Subsequent calls to {@link#isCancelled} * would always return <tt>true</tt> if this method returned <tt>true</tt>. *     * @parammayinterruptifrunning <tt>true</tt> If the thread executing this * task should is interrupted; otherw Ise, in-progress tasks is allowed * to complete *@return<tt>false</tt> If the task could not being cancelled, * typically because it has already completed Norma     lly; * <tt>true</tt> otherwise*/    BooleanCancelBooleanmayinterruptifrunning); /*** Returns <tt>true</tt> If this task is cancelled before it completed * normally. */    Booleaniscancelled (); /*** Returns <tt>true</tt> if this task completed. * Completion May is due to normal termination, a exception, or * cancellation--In all of the these cases, this method W     ill return * <TT>TRUE</TT>. */    BooleanIsDone (); /*** Waits If necessary for the computation to complete, and then * retrieves its result. */V get ()throwsinterruptedexception, executionexception; /*** Waits if necessary for in most of the given time for the computation * to complete, and then retrieves its res     Ult, if available. */V Get (LongTimeout, timeunit unit)throwsinterruptedexception, Executionexception, timeoutexception;}

The following in turn explains the effect of each method:

    • The Cancel method is used to cancel the task and returns true if the Cancel task succeeds, or False if the cancel task fails. The parameter mayinterruptifrunning indicates whether a task that is executing but not completed is allowed to be canceled, and if set to true, it means that the task in the process of execution can be canceled. If the task is completed, whether mayinterruptifrunning is true or FALSE, this method will definitely return false, that is, if canceling the completed task returns false, or if the task is executing, Returns True if the mayinterruptifrunning is set to true, or False if the mayinterruptifrunning is set to false, or if the task has not been executed, whether Mayinterruptifrunning is true or false, it must return true.
    • The IsCancelled method indicates whether the task was canceled successfully and returns true if the task was canceled successfully before it was properly completed.
    • The Isdone method indicates whether the task has completed and returns true if the task completes;
    • The Get () method is used to get the result of the execution, this method will be blocked, will wait until the task is completed before returning;
    • Get (long timeout, timeunit unit) is used to get the execution result, and if the result is not obtained within the specified time, NULL is returned directly.

This means that the future offers three functions:

1) Determine whether the task is completed;

2) ability to interrupt tasks;

3) Ability to get task execution results.

Because the future is just an interface, it is not directly used to create objects, so there is the following futuretask.

Three. Futuretask

Let's take a look at the implementation of Futuretask:

 Public class Implements Runnablefuture<v> {}

The Futuretask class implements the Runnablefuture interface, and we look at the implementation of the Runnablefuture interface:

 Public Interface extends Runnable, future<v> {    /*** Sets this future to the result of its     computation     * UN Less it has been cancelled.      */    void run ();}

It can be seen that runnablefuture inherits the Runnable interface and the future interface, and Futuretask implements the Runnablefuture interface. So it can be executed as runnable by thread, and can get callable return value as future.

The Futuretask provides 2 constructors:

 Public Futuretask (callable<v> callable) {    }public  futuretask (Runnable Runnable, V result) {    }

In fact, Futuretask is a unique implementation class for the future interface

Simple example:

Importjava.util.concurrent.*;/*** Created by Xinfengyao on 16-2-17.*/ Public classRunnablefuturetest {StaticExecutorservice Executorservice =Executors.newcachedthreadpool ();  Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {Runnabledemo ();    Futuredemo (); }    /*** runnable no return value*/    Static voidRunnabledemo () {NewThread (NewRunnable () {@Override Public voidrun () {System.out.println ("Runnable Demo:" + FIBC (20));    }}). Start (); }    /*** where runnable implements the void run () method with no return value, callable implements the V * Call () method and can return execution results.     Where runnable can be submitted to thread to wrap *, directly start a thread to execute, and callable is generally committed to Executeservice to execute. */    Static voidFuturedemo ()throwsexecutionexception, interruptedexception {/*** Submit Runnable no return value, no future data*/ Future<?> result = Executorservice.submit (NewRunnable () {@Override Public voidrun () {FIBC (20);        }        }); System.out.println ("Future result from runnable:" +result.get ()); /*** Submit callable, return value, can get return value in future*/ Future<Integer> result2 = Executorservice.submit (NewCallable<integer>() {@Override PublicInteger Call ()throwsException {returnFIBC (20);        }        }); System.out.println ("Future result from callable:" +result2.get ()); /*** Futuretask is a runnablefuture<v>, which realizes both the runnable and future<v> of the two interfaces, * In addition it can be packaged runnable (actually Converted to callable) and callable * <v>, so generally it is a complex, which can be executed directly through the thread wrapper, can also be submitted to the Executeservice to execute *, and can also be via V get         () returns the execution result, when the thread body is not completed, the main thread blocks waiting, and the result is returned directly after execution. */Futuretask<Integer> Futuretask =NewFuturetask<integer> (NewCallable<integer>() {@Override PublicInteger Call ()throwsException {returnFIBC (20);        }        }); //Submit FuturetaskExecutorservice.submit (Futuretask); System.out.println ("Future result from Futuretask:" +futuretask.get ()); }    Static intfibcintN) {if(N==0 | | n==1) {            returnN; }        returnFIBC (n-1) + FIBC (n-2); }}

Callable, Runnable, future, Futuretask

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.