13. submit method of ThreadPoolExecutor thread pool, submit of java Thread Pool

Source: Internet
Author: User

13. submit method of ThreadPoolExecutor thread pool, submit of java Thread Pool

Jdk1.7.0 _ 79

In the previous article ThreadPoolExecutor thread pool Principle and Its execute method, we mentioned the ThreadPoolExecutor principle of the thread pool and Its execute method. This article analyzes ThreadPoolExecutor # submit.

For execution of a task, sometimes we don't need it to return the result, but we need it to return the execution result. For a thread, if it does not need to return results, it will implement Runnable, and if it needs to execute results, it can implement Callable. In the thread pool, execute provides the execution of a task that does not need to return results, and the submit method can be called to return results.

Review the inheritance relationship of ThreadPoolExecutor.

  

Only the execute method is defined in the Executor interface, while the submit method is defined in the ExecutorService interface.

  

//ExecutorServicepublic interface ExecutorService extends Executor {  ...  <T> Future<T> submit(Callable<T> task);  <T> Future<T> submit(Runnable task, T result);  <T> Future<T> submit(Runnable task);  ...}

The submit method is implemented in its subclass AbstractExecutorService.

//AbstractExecutorServicepublic abstract class AbstractExecutorService implements ExecutorService {  ...  public <T> Future<T> submit(Callable<T> task) {    if (task == null) throw new NullPointerException();    RunnableFuture<T> ftask = newTaskFor(task);    execute(ftask);    return ftask;  }  public <T> Future<T> submit(Runnable task, T result) {    if (task == null) throw new NullPointerException();    RunnableFuture<T> ftask = newTaskFor(task);    execute(ftask);    return ftask;  }  public Future<?> submit(Runnable task) {    if (task == null) throw new NullPointerExeption();    RunnableFuture<Void> ftask = newTaskFor(task, null);    execute(ftask);    return ftask;   }  ...}

The submit method implemented in AbstractExecutorService is actually a template method that defines the algorithm skeleton of the submit method, and its execute is handed over to the subclass. (In many source codes, the template method mode is widely used. For details about the template method mode, see template method mode.)

Although the submit method can provide the return value of thread execution, only Callable can return the value, while the thread implementing Runnable has no return value, that is, in the preceding three methods, submit (Callable <T> task) can obtain its return value. submit (Runnable task, T result) the returned value of the thread can be indirectly obtained through the input carrier result or accurately handed over to the thread for processing, while the last method of submit (Runnable task) does not return the value, the return value is null.

The following three examples show how to use the submit method.

Submit (Callable <T> task)

package com.threadpoolexecutor;import java.util.concurrent.*;/** * ThreadPoolExecutor#sumit(Callable<T> task) * Created by yulinfeng on 6/17/17. */public class Sumit1 {    public static void main(String[] args) throws ExecutionException, InterruptedException {        Callable<String> callable = new Callable<String>() {            public String call() throws Exception {                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)

package com.threadpoolexecutor;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;/** * ThreadPoolExecutor#submit(Runnable task, T result) * Created by yulinfeng on 6/17/17. */public class Submit2 {    public static void main(String[] args) throws ExecutionException, InterruptedException {        ExecutorService executor = Executors.newSingleThreadExecutor();        Data data = new Data();        Future<Data> future = executor.submit(new Task(data), data);        System.out.println(future.get().getName());    }}class Data {    String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}class Task implements Runnable {    Data data;    public Task(Data data) {        this.data = data;    }    public void run() {        System.out.println("This is ThreadPoolExetor#submit(Runnable task, T result) method.");        data.setName("kevin");    }}

Submit (Runnable task)

package com.threadpoolexecutor;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;/** * ThreadPoolExecutor#sumit(Runnable runnables) * Created by yulinfeng on 6/17/17. */public class Submit {    public static void main(String[] args) throws ExecutionException, InterruptedException {        Runnable runnable = new Runnable() {            public void run() {                System.out.println("This is ThreadPoolExetor#submit(Runnable runnable) method.");            }        };        ExecutorService executor = Executors.newSingleThreadExecutor();        Future future = executor.submit(runnable);        System.out.println(future.get());    }}

Through the above instance, we can see that we do not need to define the type when calling submit (Runnable runnable). That is to say, although ExecutorService defines it as a generic method, in AbstractExecutorService, it is not a generic method because it does not return a value. (Related to Object, T ,? For the differences between the three, see Object, T (generic ),? Difference).

From the source code above, we can see that the three methods are almost the same. The key lies in:

RunnableFuture<T> ftask = newTaskFor(task);execute(ftask);

How does one pass a task as a parameter to newTaskFor, then call the execute method, and then return ftask?

//AbstractExecutorService#newTaskForprotected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {  return new FutureTask<T>(callable);}  protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {  return new FutureTask<T>(runnable, value);} 

It seems that a FutureTask instance is returned, and FutureTask implements the Future and Runnable interfaces. The Future interface is an implementation of the Java thread Future mode and can be used for asynchronous computing. the Runnable interface can be executed as a thread. FutureTask implements these two interfaces, which means that it represents the result of asynchronous computing and can be executed by Executor as a thread. The FutureTask is placed in the following chapter for separate parsing. Therefore, this article does not completely parse the submit method of the thread pool ThreadPoolExecutor. You must understand the Future mode of Java threads.

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.