Home Java javaTutorial Detailed explanation of the submit method of ThreadPoolExecutor thread pool in JAVA

Detailed explanation of the submit method of ThreadPoolExecutor thread pool in JAVA

Jun 30, 2017 am 10:43 AM
java submit threadpoolexecutor

The following editor will bring you a brief talk about the submit method of ThreadPoolExecutor thread pool. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

##jdk1.7.0_79

In the previous article "

ThreadPoolExecutor thread pool principle and its execute method", the principle of the thread pool ThreadPoolExecutor and its execute method were mentioned. 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 results, and for those that need to return results, its submit method can be called.

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.

//ExecutorService
public 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);
  ...
}
Copy after login

The submit method is implemented in its subclass AbstractExecutorService.

//AbstractExecutorService
public 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; 
  }
  ...
}
Copy after login

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 in many source codes, the template method pattern is widely used. 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, and 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 obtains 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());
 }
}
Copy after login

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");
 }
}
Copy after login

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());
 }
}
Copy after login

Through the above example, you can see that when calling submit(Runnable runnable), its defined type is not required, that is to say, although it is defined in ExecutorService is a generic method, but in AbstractExecutorService it is not a generic method because it has no return value. (For the differences between

Object, T, and ?, please refer to "Object, T (generic), and ? Difference 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);
Copy after login

How it passes a task as a parameter to newTaskFor and then calls execute method, and finally return ftask?

//AbstractExecutorService#newTaskFor
protected <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);
}
Copy after login

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 - "

The Future Mode in Java".

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

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles