The Callable,future,futuretask of Java concurrent programming

Source: Internet
Author: User

To create a thread:
1. Inherit thread
2. Implement Runnable
Careful observation will find void run (), which does not return a value and cannot get the result of thread execution.

Callable

A task that returns the result and may throw an exception. The implementing person defines a method called call without any parameters.

The callable interface is similar to Runnable, and both are designed for classes whose instances might be executed by another thread. However, Runnable does not return a result and cannot throw a checked exception.

V Call ()
Evaluates the result and throws an exception if the result cannot be evaluated.
Similar to the runnable feature for creating threads, but the call method has a return value
The result type of the V-call method

Future

Interface future<v>
V-The result type returned by the Get method for this future
The future represents the result of an asynchronous calculation. It provides a way to check whether the calculation is completed "IsDone ()", to wait for the completion of the calculation, and to get the result of the calculation "get ()". You can only use the Get method to get the results after the calculation is complete and, if necessary, block this method before the calculation is complete. Cancellation is performed by the Cancel method. Additional methods are provided to determine whether the task is completed normally or canceled "iscancelled ()". Once the calculation is complete, you can no longer cancel the calculation. If you use the future for the sake of cancellation and do not provide the available results, you can declare the Future<?> form type and return null as the result of the underlying task.

Futuretask

realizes the Future interface
Class futuretask<v>
Type parameter:
V-The result type returned by the Get method of this futuretask.

An asynchronous computation that can be canceled. This class provides a basic implementation of the future, taking advantage of the method of starting and canceling the calculation, the method of querying whether the calculation is complete, and the method of obtaining the result of the calculation. The result is only available when the calculation is complete, and if the calculation is not completed, the Get method is blocked. Once the calculation is complete, you cannot start or cancel the calculation again.

Method meaning
Futuretask (callable<v> callable) Creates a futuretask that executes the given callable once it is run.
Futuretask (Runnable Runnable, V result) Creates a futuretask that, once run, executes the given Runnable and schedules a successful completion when get returns the given result.
Boolean Cancel (Boolean mayinterruptifrunning) An attempt was made to cancel execution of this task.
protected void Done () The protected method is called when this task transitions to the state isDone (whether normal or canceled).
V get () If necessary, wait for the calculation to complete and then get its results.
V get (long timeout, timeunit unit) If necessary, wait for the result to be obtained (if the result is available) after the time given for the calculation to complete.
Boolean iscancelled () Returns true if the task is canceled before it is completed properly.
Boolean IsDone () Returns true if the task is completed.
void Run () Unless you have canceled this future, set it as the result of its calculation.
Protected Boolean Runandreset () Performs a calculation without setting its results, resets the future to its original state, and fails if the calculation encounters an exception or is canceled.
protected void Set (V V) The result is set to the given value unless the future has been set or canceled.
Instance

We can understand that Futuretask is a background thread that differs from the general implementation of runnable threads, Futuretask encapsulates the information, and saves the results. When we are interested in the results at any moment, you can call the Get method directly.

SwingWorker (Implementation of the Future interface) is actually a good example.
On the one hand interface to the corresponding user's mouse click events, on the one hand need to calculate time-consuming tasks (such as calculating prime numbers). If the calculation task is scheduled in the main thread, it will cause the interface to die, that is, the user's click events. So you can borrow swingwork

 Public  class testfuturetask {     Public Static void Main(string[] args)throwsException {System.out.println ("Hello world!"); Futuretask Futuretask =NewFuturetask (NewCalculatetask ()); Thread task =NewThread (Futuretask); Task.start ();//Monitor whether the calculation task is over         while(!futuretask.isdone ()) {System.out.println ("Responding to other users ' needs ...");//thread.sleep (+);}//Get results, if the result is not ready, it will block hereSystem.out.println (Futuretask.get ()); }}class Calculatetask implements callable<list<integer>>{/ * * Calculation 12321 can be added by the two prime numbers */    @Override     PublicList<integer>Pager()throwsexception{list<integer> List =NewArraylist<integer> ();LongStart = System.currenttimemillis ();intCount =0; for(inti =2; I <12321; i + +) {if(IsPrime (i))                {count++; System.out.print (i +"\ T");if(Count% -==0) {System.out.println (); }}} System.out.println ("\ n Total number of primes:"+ count); for(inti =2; I <=12321/2; i + +) {//system.out.println (i+ "," + (12321-i));            if(IsPrime (i) && IsPrime (12321-i)) {list.add (i); List.add (12321-i); }//thread.sleep (+);} System.out.println ("The calculation results are time consuming:"+ (System.currenttimemillis ()-start) +"MS");returnList } Public Static Boolean IsPrime(intPrime) {intnum = (int) math.sqrt (prime); for(inti =2; I <= math.sqrt (prime); i + +) {if(prime% i = =0){return false; }        }return true; }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The Callable,future,futuretask of Java concurrent programming

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.