Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the executor thread pool framework of Java

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to use the executor thread pool framework of Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Brief introduction of Executor framework 1. Basic introduction

In the Executor system, the thread task submission and task execution are decoupled. Executor has various powerful implementation classes, which provide a convenient way to submit the task and obtain the task execution result, encapsulate the task execution process, no longer need Thread (). Start () method, explicitly create threads and associate with task execution.

2. Scheduling model

The thread is mapped one-to-one to the operating system thread on which the service resides, and an operating system thread is created at startup; when the thread terminates, the operating system thread is also recycled.

3. Core API structure

The core interfaces and main implementation classes included in the Executor framework are shown in the following figure:

Thread pool tasks: core interfaces: Runnable, Callable interfaces and interface implementation classes

Result of the task: interface Future and implementation class FutureTask

Task execution: core interface Executor and ExecutorService interface. There are two core classes in the Executor framework that implement the ExecutorService interface, ThreadPoolExecutor and ScheduledThreadPoolExecutor.

II. Usage case 1. API basis

ThreadPoolExecutor infrastructure

Public ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {} parameter name indicates the core size of the corePoolSize thread pool. When the queue is not full Maximum number of concurrency of threads maximumPoolSize maximum size of thread pool, maximum number of concurrency that threads can tolerate after the queue is full keepAliveTime time limit for idle threads waiting for recycling unitkeepAliveTime time unit workQueue blocked queue type threadFactory creates a thread factory. Generally, when handler exceeds the work queue and thread pool by default, the task will throw an exception by default 2, initialization method ExecutorService: Executors.newFixedThreadPool () ExecutorService: Executors.newSingleThreadExecutor (); ExecutorService: Executors.newCachedThreadPool (); ThreadPoolExecutor: new ThreadPoolExecutor ()

In general, thread pools are not allowed to be created using Executors, but through ThreadPoolExecutor, which makes the running rules of thread pools clearer and avoids the risk of resource exhaustion.

3. The basic case package com.multy.thread.block08executor;import java.util.concurrent.*;public class Executor01 {/ / defines the thread pool private static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor (3Jing 10je 5000 journal TimeUnit. Second, new SynchronousQueue (), Executors.defaultThreadFactory (), new ExeHandler ()); public static void main (String [] args) {for (int I = 0; I)

< 100 ; i++){ poolExecutor.execute(new PoolTask(i)); //带返回值:poolExecutor.submit(new PoolTask(i)); } }}// 定义线程池任务class PoolTask implements Runnable { private int numParam; public PoolTask (int numParam) { this.numParam = numParam; } @Override public void run() { try { System.out.println("PoolTask "+ numParam+" begin..."); Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } } public int getNumParam() { return numParam; } public void setNumParam(int numParam) { this.numParam = numParam; }}// 定义异常处理class ExeHandler implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { System.out.println("ExeHandler "+executor.getCorePoolSize()); executor.shutdown(); }} 流程分析 线程池中线程数小于corePoolSize时,新任务将创建一个新线程执行任务,不论此时线程池中存在空闲线程; 线程池中线程数达到corePoolSize时,新任务将被放入workQueue中,等待线程池中任务调度执行; 当workQueue已满,且maximumPoolSize>

When corePoolSize, a new task creates a new thread to execute the task

When workQueue is full and the number of tasks submitted exceeds maximumPoolSize, the task is handled by RejectedExecutionHandler

When the number of threads in the thread pool exceeds corePoolSize, and the idle time beyond this part reaches keepAliveTime, the thread is recycled

If allowCoreThreadTimeOut (true) is set, the idle time of threads within the scope of corePoolSize in the thread pool will also be recycled when it reaches keepAliveTime.

Third, thread pool application

Application scenario: the verification task of batch accounts and passwords is quite common in the actual business. By initializing the thread pool, submitting the task for execution, and finally getting the processing result, this is the core idea of thread pool: saving resources and improving efficiency.

Public class Executor02 {public static void main (String [] args) {/ / initialize the verification task List checkTaskList = new ArrayList (); initList (checkTaskList); / / define thread pool ExecutorService executorService; if (checkTaskList.size () < 10) {executorService = Executors.newFixedThreadPool (checkTaskList.size ());} else {executorService = Executors.newFixedThreadPool (10) } / / batch processing List results = new ArrayList (); try {results = executorService.invokeAll (checkTaskList);} catch (InterruptedException e) {Thread.currentThread () .interrupt () } / / View the result for (Future result: results) {try {System.out.println (result.get ()); / / System.out.println (result.get (10000 last TimeUnit. Second));} catch (Exception e) {e.printStackTrace () }} / / close thread pool executorService.shutdownNow ();} private static void initList (List checkTaskList) {checkTaskList.add (new CheckTask ("root", "123")); checkTaskList.add (new CheckTask ("root1", "1234")); checkTaskList.add (new CheckTask ("root2", "1235") }} / / Verification task class CheckTask implements Callable {private String userName; private String passWord; public CheckTask (String userName, String passWord) {this.userName = userName; this.passWord = passWord;} @ Override public Boolean call () throws Exception {/ / verify account + password if (userName.equals ("root") & & passWord.equals ("123")) {return Boolean.TRUE } return Boolean.FALSE;}}

Thread pool is mainly used to solve the problem of thread life cycle overhead and insufficient resources. multiple task threads are reused through thread pool, thread creation is also allocated to multiple tasks, and idle threads can be used when most tasks are submitted, so eliminate the overhead caused by frequent thread creation.

This is the end of the content of "how to use Java's executor thread pool framework". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report