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 realize the construction method of Java thread pool

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to realize the construction method of Java thread pool". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn how to realize the construction method of Java thread pool.

I. Preface

In order to realize concurrent programming, the concept of process is introduced. A process is equivalent to a task of the operating system. When multiple processes execute tasks at the same time, concurrent programming is realized and can be executed more quickly.

However, because the process is not lightweight enough, the resources consumed by creating a process and destroying a process can not be ignored. If the number of processes is small, these resource consumption is acceptable, but if the processes are created and destroyed frequently. It's a lot of money.

What are we going to do?

In order to solve this problem, a lighter tool, threads, has been introduced.

Threads are also called lightweight processes. Its creation and destruction consume less resources than processes. But what if there are a large number of tasks and multithreading can't help creating and destroying them frequently? At this point, the thread pool comes out to solve the problem!

Second, what is the thread pool?

A thread pool is something similar to a Java string constant pool.

Use Thread VS do not use Thread

When using a thread, fetch a thread directly from the pool.

Put a thread in the pool when it is not in use

Everyone knows that the process of finding a job is something like this.

Send in your resume

Written examination

Interview

Offer

When we finish the interview, there will be two situations.

Yes, the company will call you and send you offer.

Failed, and the general company does not tell you that you have failed, but did not inform you that you have not, this is because the company may put you in their "talent pool".

Suppose the company is looking for 50 people, and in the autumn recruitment, send offer to 50 people. But in fact, only 35 people came to report on the job. At this time, the remaining 15 people directly fished out 15 from the talent pool and sent offer directly.

After a period of time, the company suddenly called you and informed you that you were hired. Would you like to come? This operation is equivalent to a thread to be used, directly out of the pool to use.

This is an example of looking for a job to describe what thread pool probably means.

Third, what are the parameters of the thread pool constructor ThreadPoolExecutor?

In the Alibaba java Development Manual, it is pointed out that thread resources must be provided through the thread pool, and the creation of threads shown in the application is not allowed, so on the one hand, the creation of threads is more standardized, and the number of threads can be reasonably controlled; on the other hand, thread details management is handed over to thread pool processing, which optimizes the cost of resources.

The "ThreadPoolExecutor" class is a set of classes provided by the Java standard library for using thread pools.

There are four ways to construct ThreadPoolExecutor. Each contains different parameters and different scenarios are used.

We will introduce it with the construction method with the most parameters.

ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor (int corePoolSize,int maximumPoolSize, long keepAliveTime, TimeUnit unit,BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)

Number of 1.corePoolSize core threads

Maximum number of threads in 2.maximumPoolSize

The number of core threads and the maximum number of threads may not be well understood. Here is an example of an employee going to work.

The number of core threads, that is, regular employees in the company, allows them to fish for a while. If you get caught, you won't be fired. (equivalent to threads in the thread pool that will not be destroyed even if they do nothing)

The maximum number of threads is the number of regular employees + temporary workers in the company, but the temporary workers here will be fired when they touch the fish at a certain time. (equivalent to thread destruction in the thread pool)

3.keepAliveTime describes how long temporary workers can touch fish.

4.unit is a unit of time, that is, the unit of keepAliveTime.

5.workQueue blocks the queue and organizes the tasks to be performed by the thread pool

How 6.threadFactory threads are created. This parameter is used to set how different threads are created.

7.RejectedExecutionHandler handler reject policy. When the task queue is full, the new task comes again, what to do at this time?

(1): forget the latest task.

(2): forget the oldest task.

(3): blocking waiting

(4) Open pendulum: throw an exception

Because ThreadPoolExecutor is complex to use, it has up to 7 parameters. The standard library provides programmers with a set of other classes for this purpose. It is equivalent to another layer of encapsulation of ThreadPoolExecutor.

1.newFixedThreadPool: create a thread pool with a fixed number of threads.

ExecutorService Service1 = Executors.newFixedThreadPool (20)

2.newCachedThreadPool: create a variable number of thread pools

ExecutorService Service2 = Executors.newCachedThreadPool ()

3.newSingleThreadExecutor: create a thread pool with only one thread

ExecutorService Service3 = Executors.newSingleThreadExecutor ()

4.newScheduledThreadPool: create a thread pool that sets the latency.

ExecutorService Service4 = Executors.newScheduledThreadPool (20); fourth, simulate a thread pool to simulate the core operation of a thread pool:.: add tasks to the thread pool-submit. .: use the Worker class to describe a worker thread and Runnable to describe a task. .: create a BlockingQueue blocking queue to organize all tasks. .: all each Worker has to do is to constantly get tasks from the blocking queue and execute them. .: specify the maximum number of threads in the thread pool, and if you exceed this number, do not continue to create threads.

Code implementation:

Let's create a thread pool and have it keep creating the process to print hello

Import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.ThreadPoolExecutor;/** * Created with IntelliJ IDEA. * * @ Description: simulate the use of thread pool * / public class ThreadDemo0327_2 {public static void main (String [] args) throws IOException, InterruptedException {ThreadPoll threadPoll=new ThreadPoll (); for (int I = 0; I)

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

Development

Wechat

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

12
Report