Java Learning runnable, callable, future, Futuretask

Source: Internet
Author: User

Reprint: Http://www.jianshu.com/p/cf12d4244171Runnable
Public interface Runnable {public    abstract void run ();

  

Runnable's code is very simple, it is an interface and there is only one run (), creating a class to implement it, putting some time-consuming actions in it, and then using a thread to execute the Runnable implementation class to achieve multithreading.

Callable
Public interface Callable<v> {    V call () throws Exception;}

  

The callable code is also very simple, but the difference is that it is a generic interface, and the type returned by the call () function is the type of V to create the callable.
Learning callable contrasts with runnable so that it can be understood very quickly. The function of callable and runnable is similar, callable is powerful, it can return a value after being executed by thread, and can throw an exception.

Futurefuture Implementation Code
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 future is an interface that defines the future for the execution of specific runnable or callable tasks, whether the query task is canceled, whether the query is complete, and the results are obtained.

Future basic usage:
Class Mycallable implements callable<string>{    @Override public    String call () throws Exception {        System.out.println ("Do some time-consuming tasks ...");        Thread.Sleep (the);        return "OK";}    } public class Futuresimpledemo {public    static void Main (string[] args) throws Interruptedexception, executionexception {        Executorservice executorservice = Executors.newcachedthreadpool ();        future<string> future = Executorservice.submit (New mycallable ());        System.out.println ("dosomething ...");        System.out.println ("Get asynchronous task Return Result:" + future.get ());        System.out.println ("completed!");}    }

  

Above is the basic usage code of the future and run, we can know:

    1. Threads are part of the asynchronous compute model, so you can't get a method return value directly from another thread. That's when the future comes out.
    2. Futrue can monitor when the target thread calls call, and when you invoke the Get () method of the future to get the result, the current thread begins to block, and the call method ends the return result.
    3. The future reference object points to the actual futuretask.

In other words, the future can get the return value of another thread's task method, summing up a sentence.

FUTURETASKFUTURETASK Inheritance Structure

The parent class of Futuretask is Runnablefuture, and Runnablefuture inherits the two interfaces Runnbale and Futrue

public class Futuretask<v> implements Runnablefuture<v>public interface Runnablefuture<v> extends Runnable, future<v>

  

Futuretask Construction Method
Public Futuretask (callable<v> callable) {        if (callable = = null)            throw new NullPointerException ();        this.callable = callable;        This.state = NEW;       Ensure visibility of callable}public futuretask (Runnable Runnable, V result) {        this.callable = executors.callable ( runnable, result);        This.state = NEW;       Ensure visibility of callable}

  

Here we can learn:

    1. Futuretask is ultimately a task that performs the callable type.
    2. If the constructor argument is runnable, it is converted to the callable type by the Executors.callable method.

Next we look at the Executors.callable method code

public static <T> callable<t> callable (Runnable task, T result) {        if (task = = null)            throw new Nullpoin Terexception ();        return new runnableadapter<t> (task, result);}

  

The code is simple and returns a Runnableadapter instance directly.

Next we look at the Runnableadapter method code

    /**     * A callable that runs given task and returns given result     */    static final class runnableadapter<t> Implements Callable<t> {        final Runnable task;        Final T result;        Runnableadapter (Runnable task, T result) {            this.task = task;            This.result = result;        }        Public T-Call () {            task.run ();            return result;        }    }

  

Can be learned that:

    1. Runnableadapter is a static inner class of Futuretask and implements callable, which means that Runnableadapter is a callable subclass.
    2. The Call method implementation code is to execute the Runnable run method and return the construct Futuretask incoming result parameter.
Futuretask Basic Usage
public class Callableandfuture {public    static void Main (string[] args) {        callable<integer> callable = new C Allable<integer> () {public            Integer call () throws Exception {                return new Random (). Nextint ();}        } ;        futuretask<integer> future = new futuretask<integer> (callable);        New Thread (Future). Start ();        try {            Thread.Sleep (3000);//may do something            System.out.println (Future.get ());        } catch (Interruptedexception E ) {            e.printstacktrace ();        } catch (Executionexception e) {            e.printstacktrace ();}}    }

  

Futuretask Summary

Futuretask implements two interfaces, runnable and future, so it can be executed as a runnable thread, and can be used as the future to get callable return value, so what is the benefit of using this combination? Assuming that there is a time-consuming logic to calculate and return this value, and that this value is not needed immediately, then you can use this combination to calculate the return value with another thread, and the current thread can do other things before using this return value, and then get it through the future when this return value is needed!

Java Learning runnable, callable, future, Futuretask

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.