13.ThreadPoolExecutor Line Cheng Submit method

Source: Internet
Author: User

jdk1.7.0_79

The principle of thread pool Threadpoolexecutor and its Execute method are mentioned in the previous article, "Threadpoolexecutor thread pool principle and its Execute method". This article resolves Threadpoolexecutor#submit.

For the execution of a task sometimes we don't need it to return results, but there is a return execution result we need it. For threading, Runnable is implemented if you don't need it to return results, and callable can be implemented if you need to execute the results. The online pool is also executed to provide a task execution that does not need to return a result, and the Submit method can be called for the result to be returned.

Review the inheritance relationship of Threadpoolexecutor.

  

Only the Execute method is defined in the executor interface, and the Submit method is defined in the Executorservice interface.

  

// Executorservice  Public Interface extends Executor {...  <T> future<t> Submit (callable<t> Task);  <T> future<t> Submit (Runnable task, T result);  <T> future<t> Submit (Runnable Task); ...}

And in its subclass Abstractexecutorservice implements the Submit method.

//Abstractexecutorservice Public Abstract classAbstractexecutorserviceImplementsExecutorservice {... Public<T> future<t> Submit (callable<t>Task) {if(Task = =NULL)Throw NewNullPointerException (); Runnablefuture<T> Ftask =newtaskfor (Task);    Execute (ftask); returnFtask; } Public<T> future<t>Submit (Runnable task, T result) {if(Task = =NULL)Throw NewNullPointerException (); Runnablefuture<T> Ftask =newtaskfor (Task);    Execute (ftask); returnFtask; } PublicFuture<?>Submit (Runnable Task) {if(Task = =NULL)Throw Newnullpointerexeption (); Runnablefuture<Void> ftask = newtaskfor (Task,NULL);    Execute (ftask); returnFtask; } ...}

The Submit method implemented in Abstractexecutorservice is actually a template method that defines the algorithm skeleton of the Submit method, whose execute is given to the subclass. (You can see in a lot of source code, template method pattern is used extensively, about template method mode can refer to "template method mode")

Although the Submit method provides the return value of the thread execution, the return value is only implemented callable, and the thread that implements Runnable has no return value, that is, in the 3 methods above, the Submit (callable<t> Task) Can obtain its return value, submit (Runnable task, T result) can indirectly get the return value of the thread through the passed-in vector result, or give it to the thread to handle it accurately, and the last method submit (Runnable Task) There is no return value, even if the return value of the fetch is NULL.

Here are 3 examples to get a feel for the Submit method.

  Submit (callable<t> Task)

 PackageCom.threadpoolexecutor;Importjava.util.concurrent.*;/*** Threadpoolexecutor#sumit (callable<t> Task) * Created by Yulinfeng on 6/17/17.*/ Public classSumit1 { Public Static voidMain (string[] args)throwsExecutionexception, interruptedexception {callable<String> callable =NewCallable<string>() {             PublicString Call ()throwsException {System.out.println ("This is Threadpoolexetor#submit (callable<t> Task) method."); return"Result";        }        }; Executorservice Executor=Executors.newsinglethreadexecutor (); Future<String> future =Executor.submit (callable);    System.out.println (Future.get ()); }}

  Submit (Runnable task, T result)

 PackageCom.threadpoolexecutor;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;/*** Threadpoolexecutor#submit (Runnable task, T result) * Created by Yulinfeng on 6/17/17.*/ Public classSubmit2 { Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {executorservice executor=Executors.newsinglethreadexecutor (); Data Data=NewData (); Future<Data> future = Executor.submit (NewTask (data), data);    System.out.println (Future.get (). GetName ()); }}classData {String name;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }}classTaskImplementsRunnable {data data;  PublicTask (data data) { This. data =data; }     Public voidrun () {System.out.println ("This is Threadpoolexetor#submit (Runnable task, T Result) method."); Data.setname ("Kevin"); }}

  Submit (Runnable Task)

 PackageCom.threadpoolexecutor;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;/*** Threadpoolexecutor#sumit (Runnable runnables) * Created by Yulinfeng on 6/17/17.*/ Public classSubmit { Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {Runnable Runnable=NewRunnable () { Public voidrun () {System.out.println ("This is Threadpoolexetor#submit (Runnable Runnable) method.");        }        }; Executorservice Executor=Executors.newsinglethreadexecutor (); Future=Executor.submit (runnable);    System.out.println (Future.get ()); }}

The above example allows you to see that the definition type is not required when calling submit (Runnable Runnable), that is, although a generic method is defined in Executorservice. In Abstractexecutorservice, however, it is not a generic method because it has no return value. (For the difference between object, T, and?, refer to "object in Java, T (generics),??)".

From the above source can be seen, the three methods are almost the same, the key lies in:

runnablefuture<t> ftask = newtaskfor (Task); execute (ftask);

How does it pass a task as an argument to Newtaskfor, and then call the Execute method and finally return to Ftask?

 // abstractexecutorservice#newtaskfor  protected  <T> runnablefuture<t> newtaskfor (callable<t > callable) { new  futuretask<t> (callable);  protected  <T> runnablefuture<t>  Newtaskfor (Runnable Runnable, T value) { return< /span> new  futuretask<t> (runnable, value );} 

It appears that a Futuretask instance has been returned, and Futuretask implements the future and runnable interfaces. The future interface is the implementation of the Java thread's future pattern, which can be used for asynchronous computations, and the implementation of the Runnable interface represents the execution as a thread. Futuretask implementation of these two interfaces means that it represents the result of an asynchronous computation and can be executed as a thread to executor. The futuretask is put into the next chapter separate parsing. Therefore, this article for thread pool Threadpoolexecutor thread pool Submit method parsing is not complete, you must understand the Java thread of the future mode.

13.ThreadPoolExecutor Line Cheng Submit method

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.