JAVA Future-Class explanation

Source: Internet
Author: User
Tags protected constructor thread class

1. Application Scenarios for the future

In concurrent programming, we often use non-blocking models, in the previous multi-threaded three implementations, whether inheriting the thread class or implementing the Runnable interface, there is no guarantee to get to the previous execution results. By implementing the callback interface and using the future to receive multi-threaded execution results.

The future represents the result of an asynchronous task that may not have been completed, and for that result you can add callback to make the appropriate action after the task executes successfully or fails.

For example: To eat breakfast, ordered steamed buns and cold dishes, steamed buns need to wait 3 minutes, cold dishes only 1 minutes, if it is a serial implementation, in the early time to eat to wait 4 minutes, but because you are waiting for steamed buns, you can prepare cold dishes at the same time, so in preparation for the process, you can prepare steamed buns, This only takes 3 minutes to wait. The future of this pattern is the latter mode of execution.

2. The class diagram structure of the future

The future interface defines the main 5 interface methods, with Runnablefuture and schedualfuture inheriting this interface, and Completefuture and Forkjointask inheriting this interface.

Runnablefuture

This interface inherits both the future interface and the Runnable interface, and after successful execution of the run () method, the results can be accessed through the future. The implementation of this interface is Futuretask, a cancellation of asynchronous computation, this class provides a basic implementation of the future, the following is the demo of the implementation of this class, it implements the start and cancel a calculation, query whether the calculation is completed, restore the results of the calculation. The results of the calculation can only be recovered if the calculation has been completed. If the calculation is not completed, the Get method will block and once the calculation is complete, the calculation will not be restarted and canceled unless the Runandreset method is called.

Futuretask can be used to wrap a callable or Runnable object, because it implements the Runnable interface, and it can be passed to executor for execution. To provide a singleton class, this class provides a protected constructor when creating a custom work class.

Schedualfuture

This interface indicates that a delay behavior can be canceled. Usually a scheduled future is the result of a scheduled task Schedualedexecutorservice

Completefuture

A future class is the completion of the display and can be used as a completion level, triggering supported dependency functions and behaviors through its completion. Only one succeeds when two or more threads are about to perform a completion or cancel operation.

Forkjointask

Task-based abstract classes that can be executed by Forkjoinpool. A forkjointask is similar to a thread entity, but is lightweight relative to the thread entity. A large number of tasks and subtasks are hung up by real threads in the Forkjoinpool pool at the expense of certain usage restrictions.

3. The Main method of future

The future interface consists of 5 main methods

The Get () method can return a result when the task is finished, and if the call is not finished, the thread will be blocked until the task finishes executing get (long timeout,timeunit Unit) long wait timeout will return the result the Cancel (Boolean mayinterruptifrunning) method can be used to stop a task, If the task can be stopped (judged by mayinterruptifrunning), you can return true if the task is completed or stopped, or the task cannot be stopped. The False.isdone () method is returned to determine whether the current method completes the Iscancel () method to determine whether the current method cancels 4. Future Sample Demo

Demand scenario: While the breakfast process, steamed bun takes 3 seconds, the cold dish needs 1 seconds, the common multithreading takes four seconds to complete. Wait for the cold dish, wait for the steamed bun, because when the cold dish, the ordinary multithreading starts the start () method, executes the concrete method in the run (), does not return the result, so if has to wait for the return result, must be 1 seconds end only then to know the result.

Common Multithreading:
 public  class  bumthread extends   thread{@Override  public  void   run () { try   {thread.sleep ( 1000*3);        System.out.println ( "Bun Ready to complete"  catch   (interruptedexception e) {E.PR        Intstacktrace (); }    } }
 Public class extends thread{        @Override    publicvoid  run () {        try  {            Thread.Sleep (+);            System.out.println ("cold dish ready to complete");         Catch (interruptedexception e) {            e.printstacktrace ();     }}}
     Public Static voidMain (string[] args)throwsinterruptedexception {LongStart =System.currenttimemillis (); //wait for the cold dish--you have to wait for the return result, so call the Join methodThread T1 =NewColddishthread ();        T1.start ();                T1.join (); //wait for the bun--you have to wait for the result to return, so call the Join methodThread t2 =NewBumthread ();        T2.start ();                T2.join (); LongEnd =System.currenttimemillis (); System.out.println ("Ready to finish:" + (end-start)); }
Adopt Future Mode:
     Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {LongStart =System.currenttimemillis (); //wait for cold dishesCallable CA1 =Newcallable () {@Override PublicString Call ()throwsException {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }                return"Cold dishes ready.";        }        }; Futuretask<String> FT1 =NewFuturetask<string>(CA1); NewThread (FT1). Start (); //wait for the bun--you have to wait for the result to return, so call the Join methodCallable CA2 =Newcallable () {@Override PublicObject Call ()throwsException {Try{Thread.Sleep (1000*3); } Catch(interruptedexception e) {e.printstacktrace (); }                    return"The buns are ready.";        }        }; Futuretask<String> ft2 =NewFuturetask<string>(Ca2); NewThread (ft2). Start ();        System.out.println (Ft1.get ());                System.out.println (Ft2.get ()); LongEnd =System.currenttimemillis (); System.out.println ("Ready to finish:" + (end-start)); }

Explain the future in Java, the principle of futuretask, and the use of the thread pool 74262818

JAVA Future-Class explanation

Related Article

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.