Java.util.concuttent Callable Future Detailed

Source: Internet
Author: User

In the traditional multi-threaded implementation (inherited thread and implementation runnable) can not directly get the results of the execution of the thread, if you need to get execution results, you have to share variables or use the way of thread communication to achieve the effect, so it is more cumbersome to use.

Starting with Java 1.5, callable and the future two interfaces are available in the Java.util.concurrent package, which allows them to get the results of the task execution after the task is completed.

Callable

Callable is roughly similar to Runnable's function, and there is a call () function in callable, but the call () function has a return value , and the runnable run () function cannot return the result to the client program.

Future

Executor is the runnable and callable dispatch container, the futureis for the specific runnable or callable task execution results

Cancellation, whether the query is complete, gets the results, and sets the result action . The Get method blocks until the task returns a result.

Public interface Future<v> {    Boolean cancel (Boolean mayinterruptifrunning);    Boolean iscancelled ();    Boolean isDone ();    V get () throws Interruptedexception, Executionexception;    V get (long timeout, timeunit unit)        throws Interruptedexception, Executionexception, TimeoutException;}
    • 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, Returns true regardless of whether mayinterruptifrunning is true or false.
    • 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:

    • Determine if the task is complete
    • Ability to interrupt tasks
    • Ability to get the execution results of a task
Future and Futuretask differencesThe future is an interface,The Futuretask class is an implementation class for the future and implements the runnable, so that Futuretask can be passed to the thread object threads in a new thread execution. So it can be executed through the Excutor (thread pool), or it can be passed to the thread object. If you need to do more time-consuming operations in the main thread, but do not want to block the main thread, you can hand these jobs to the future object in the background, when the main thread in the next need, you can get background job calculation results or execution status.

Futuretask is designed to compensate for the lack of thread, which allows the programmer to know exactly when a thread is executing and to get the results returned after the thread has finished executing (if necessary).

Futuretask is an asynchronous computational task that can be canceled . Its calculation is achieved through callable, which is equivalent to the runnable that can carry the result, and has three states: Wait, run, and finish. Completion includes all calculations ending in any way, including normal ends, cancellations, and exceptions.

The executor framework uses Futuretask to accomplish asynchronous tasks and can be used to perform any potentially time-consuming calculations. The General Futuretask is used for time-consuming computations, and the main thread can get the results after completing its own tasks.

Futuretask is used for time-consuming computations, and the main thread can get results after completing its own tasks .

Example1:

Package Cn.com.example.concurrent.future;import java.util.concurrent.*;/** * Created by Jack on 2017/1/24. */public class Runnablefuturetask {/** * executorservice */static Executorservice Mexecutor = Executors.ne    Wsinglethreadexecutor ();        /** * @param args */public static void main (string[] args) {Runnabledemo ();    Futuredemo (); }/** * runnable, no return value */static void Runnabledemo () {New Thread (new runnable () {@Overri            De public void Run () {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 void Futuredemo () {try {/** * commit runnable no return value, future no data */     future<?> result = Mexecutor.submit (new Runnable () {           @Override public void Run () {FIBC (20);            }            });            System.out.println ("Future result from runnable:" + result.get ()); /** * Commit callable, have return value, can get return value in future */future<integer> RESULT2 = mexecutor.sub                    MIT (New callable<integer> () {@Override public Integer call () throws Exception {                return FIBC (20);            }            });            System.out.println ("Future result from callable:" + result2.get ()); /** * Futuretask is a runnablefuture<v&gt, that realizes the Runnbale and realizes the futrue<v> both interfaces, * In addition it can also be packaged Runnab             Le (which is actually converted to callable) and callable * <v&gt, so generally it is a conforming body, which can be executed directly by thread wrapper, or submitted to Executeservice for execution             *, and can also return the execution result through V get (), when the thread body is not completed, the main thread is blocked waiting, and the result is returned directly after execution. */futuretask<integer> Futuretask = new Futuretask<integeR> (New callable<integer> () {@Override public I                        Nteger call () throws Exception {return fibc (20);            }                    });            Submit Futuretask Mexecutor.submit (Futuretask);        System.out.println ("Future result from Futuretask:" + futuretask.get ());        } catch (Interruptedexception e) {e.printstacktrace ();        } catch (Executionexception e) {e.printstacktrace ();  }}/** * Efficient Fibonacci sequence, time-consuming operation * @param num * @return */static int fibc (int num) {if (num = = 0)        {return 0;        } if (num = = 1) {return 1;    } return FIBC (num-1) + FIBC (num-2); }}

Results:

Runnable demo:6765future result from runnable:nullfuture result from callable:6765future result from futuretask:67 65

Example2:

Package Cn.com.example.concurrent.future;import java.util.random;import java.util.concurrent.*;/** * Created by Jack On 2017/1/24.        */public class Runnablefuturetask {public static void main (string[] args) {//Initialize a callable object and Futuretask object        Callable Paccount = new Privateaccount ();        Futuretask futuretask = new Futuretask (paccount);        Use Futuretask to create a thread paccountthread = new Thread (futuretask);        System.out.println ("Futuretask thread now starts, startup time:" + system.nanotime ());        Paccountthread.start ();        System.out.println ("Main thread starts to perform other tasks");        Get total amount from other accounts int totalmoney = new Random (). Nextint (100000);        System.out.println ("Now your total amount in other accounts is" + Totalmoney);        System.out.println ("Waiting for the total amount of the private account to be counted ...");                Tests whether the background calculation thread is complete, waits while (!futuretask.isdone ()) {try {Thread.Sleep (500) if not completed);            System.out.println ("Private account calculation not completed continue waiting ...");         } catch (Interruptedexception e) {       E.printstacktrace ();        }} System.out.println ("The Futuretask thread has finished calculating, this time is" + system.nanotime ());        Integer Privateaccountmoney = null;        try {Privateaccountmoney = (Integer) futuretask.get ();        } catch (Interruptedexception e) {e.printstacktrace ();        } catch (Executionexception e) {e.printstacktrace ();    } System.out.println ("Your current total amount is:" + Totalmoney + privateaccountmoney.intvalue ());    }}class Privateaccount implements callable {Integer Totalmoney;        @Override public Object Call () throws Exception {Thread.Sleep (5000);        Totalmoney = new Integer (new Random (). Nextint (10000));        System.out.println ("You currently have" + Totalmoney + "in your private account");    return Totalmoney; }}

Results:

The Futuretask thread starts now and starts at: 88171383410225 The main thread starts to perform other tasks now your total amount in other accounts is 2838 waiting for the total amount of the private account to be counted ... Private account calculation not completed continue waiting ... Private account calculation not completed continue waiting ... Private account calculation not completed continue waiting ... Private account calculation not completed continue waiting ... Private account calculation not completed continue waiting ... Private account calculation not completed continue waiting ... Private account calculation not completed continue waiting ... Private account calculation not completed continue waiting ... Private account calculation not completed continue waiting ... You currently have 9238 private account calculation not completed in your private account continue to wait ... futuretask thread is calculated, this time is 88176389195218 your current total amount is: 28389238

Java.util.concuttent Callable Future Detailed

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.