"Original" Java concurrent programming--callable and future source code research

Source: Internet
Author: User
Tags thread class

Java Multi-threaded implementation of the main three kinds: inherit the thread class, implement Runnable interface, use Executorservice, callable, the future implementation has the result of multithreading. There are no return values for the first two methods after the thread has finished executing, only the last one with the return value.

Thread and runnable are not discussed. There are too many places to find their own inquiry.

Focus on callable and future,

The first piece of code:

Package Com.future.chenjun.test;import Java.util.concurrent.callable;import Java.util.concurrent.executionexception;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.future;public class Test {public static void main (string[] args) {Executorservice executorservice = Executors.newcachedthreadpool (); MyTask MyTask = new MyTask (); future<integer> result = Executorservice.submit (MyTask); Executorservice.shutdown (); try {thread.sleep (1000);} catch (Interruptedexception E1) {e1.printstacktrace ();} System.out.println ("Main thread is executing task"); try {System.out.println ("task run result" + Result.get ())} catch (Interruptedexception e) { E.printstacktrace ();} catch (Executionexception e) {e.printstacktrace ();} System.out.println ("All Tasks Completed");}} Class MyTask implements callable<integer> {@Overridepublic Integer call () throws Exception {System.out.println (" Sub-threads are being computed "); thread.sleep; int sum = 0;for (int i = 0; i <; i++) sum + = I;return sum;}}

It's important to first analyze the first line of the main () function.

Executorservice Executorservice = Executors.newcachedthreadpool ();
Naturally leads to the problem 1:executorservice itself is an interface, that
Executorservice which implementation class does this reference point to? This problem so easy, directly into the JDK source to see the results
We see the implementation code as follows:
    public static Executorservice Newcachedthreadpool () {        return new Threadpoolexecutor (0, Integer.max_value,                                      60L , Timeunit.seconds,                                      new synchronousqueue<runnable> ());    }

The answer at a glance, according to the polymorphic principle undoubtedly this

Threadpoolexecutor is the Executorservice subclass.
Well, this is the question, remember the conclusion:
The Clue 1:threadpoolexecutor is the Executorservice subclass.
future<integer> result = Executorservice.submit (MyTask);

  

Change the form a little bit, as follows
future<integer> result = Executorservice.submit (new callable<integer> () {    @Override    public Integer call () throws exception{            }    });

  

Look, similar to the following code

New Thread (New Runnable () {//anonymous inner class implementation xxx
public void Run () {
}
});

OK, let's see what this submit has done.

I entered the threadpoolexecutor inside a look, lying in the groove, found there is no way to submit, the hell

Don't worry, I'll flip. Threadpoolexecutor Class declarations

Find the following statement

public class Threadpoolexecutor extends Abstractexecutorservice

I am curious to open the abstract class Abstractexecutorservice.class source, it is this submit hidden here

Open up ....

Finally found the Submit method, as follows

Public <T> future<t> Submit (callable<t> Task) {
  

if (task = = null) throw new NullPointerException ();
runnablefuture<t> ftask = newtaskfor (Task);
Execute (ftask);
return ftask;

}

Then we naturally have to figure out what the hell this runnablefuture is, open its source code, we see:

Public interface runnablefuture<v> extends Runnable, future<v> {    /** * sets this future to the     result of its computation     * unless it has been cancelled.     *    /void run ();

So, he's runnable, Future<v> 's sub-interface.

For the time being, take a look.



"Original" Java concurrent programming--callable and future source code research

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.