search
HomeJavajavaTutorialSubmit method of ThreadPoolExecutor thread pool

Submit method of ThreadPoolExecutor thread pool

Jun 26, 2017 am 11:33 AM
submitmethodthread

jdk1.7.0_79

## In the previous article "ThreadPoolExecutor thread The principle of the thread pool ThreadPoolExecutor and its execute method are mentioned in "Pool Principle and Its Execute Method". This article analyzes ThreadPoolExecutor#submit.

For the execution of a task, sometimes we don’t need it to return results, but there are times when we need its return execution results. For a thread, if it does not need to return a result, it can implement Runnable, and if it needs to execute the result, it can implement Callable. In the thread pool, execute also provides a task execution that does not need to return a result, and its submit method can be called for those that need to return a result.

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);
  ...
}</t></t></t></t></t></t></t>
 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; 
  }
  ...
}</void></t></t></t></t></t></t></t>
The submit method implemented in AbstractExecutorService is actually a template method that defines the algorithm skeleton of the submit method, and its execution is handed over to the subclass. (It can be seen that the template method pattern is widely used in many source codes. For the template method pattern, please refer to "Template Method Pattern")

Although the submit method can provide the return value of thread execution, only Callable is implemented There will be a return value, but the thread that implements Runnable has no return value. That is to say, among the above three methods, submit(Callable task) can get its return value, submit(Runnable task, T result) can indirectly obtain the return value of the thread through the incoming carrier result or to be precise, hand it over to the thread for processing. The last method, submit (Runnable task), has no return value. Even if it gets its return value, it will be null. .

Below are three examples to get a feel for the submit method.

 submit(Callable 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());
    }
}</string></t></string></string></t>

 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");
    }
}</data>

 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());
    }
}
From the above example, we can see that when calling submit(Runnable runnable), its defined type is not required. That is to say, although it is defined as a generic method in ExecutorService, it is not generic in AbstractExecutorService. method because it has no return value. (For the differences between Object, T, and ?, please refer to "The Difference between Object, T (Generics), and ? in Java").

As you can see from the source code above, these three methods are almost the same. The key lies in:

RunnableFuture<t> ftask = newTaskFor(task);
execute(ftask);</t>
How it passes a task as a parameter to What about newTaskFor, then calling the execute method, and finally returning 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);
}</t></t></t></t></t></t></t>
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, which can be used for asynchronous calculations. Implementing the Runnable interface means that it can be executed as a thread. FutureTask implements these two interfaces, which means that it represents the result of asynchronous calculation and can be handed over to the Executor as a thread for execution. FutureTask will be analyzed separately in the next chapter. Therefore, this article's analysis of the submit method of the thread pool ThreadPoolExecutor thread pool is not complete. You must understand the Future mode of Java threads - "14. Future Mode in Java".

The above is the detailed content of Submit method of ThreadPoolExecutor thread pool. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)