


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.
//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); ... }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; } ... }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
Below are three examples to get a feel for the submit method.
submit(Callablepackage 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 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);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); }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!

概念Python中已经有了threading模块,为什么还需要线程池呢,线程池又是什么东西呢?以爬虫为例,需要控制同时爬取的线程数,例子中创建了20个线程,而同时只允许3个线程在运行,但是20个线程都需要创建和销毁,线程的创建是需要消耗系统资源的,有没有更好的方案呢?其实只需要三个线程就行了,每个线程各分配一个任务,剩下的任务排队等待,当某个线程完成了任务的时候,排队任务就可以安排给这个线程继续执行。这就是线程池的思想(当然没这么简单),但是自己编写线程池很难写的比较完美,还需要考虑复杂情况下的

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

线程池基本原理线程池的原理如下图:说明:当前运行的线程少于corePoolSize,则创建新线程来执行任务。运行的线程等于或多于corePoolSize,则将任务添加到队列中。当任务队列已满,则在非corePool中创建新的线程来处理任务。创建新线程将使当前运行的线程超出maximumPoolSize,任务将被拒绝,并调用RejectedExecutionHandler.rejectedExecution()方法。线程池拒绝策略线程池为我们提供了四种拒绝策略分别是:CallerRunsPolic

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

在《阿里巴巴java开发手册》中指出了线程资源必须通过线程池提供,不允许在应用中自行显示的创建线程,这样一方面是线程的创建更加规范,可以合理控制开辟线程的数量;另一方面线程的细节管理交给线程池处理,优化了资源的开销。而线程池不允许使用Executors去创建,而要通过ThreadPoolExecutor方式,这一方面是由于jdk中Executor框架虽然提供了如newFixedThreadPool()、newSingleThreadExecutor()、newCachedThreadPool()

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
