Home >Java >javaTutorial >How to implement the construction method of Java thread pool
In order to realize concurrent programming, the concept of process was introduced. A process is equivalent to a task of the operating system. Multiple processes execute tasks at the same time, thus achieving concurrent programming and enabling faster execution.
But because the process is not lightweight enough, the resources consumed by creating and destroying a process cannot be ignored. If the number of processes is not large, these resource consumption are acceptable, but if processes are frequently created and destroyed. That’s a lot of expense.
What should we do?
In order to solve this problem, people have introduced a lighter tool-thread.
Threads are also called lightweight processes. Its creation and destruction consume less resources than a process. But what if there are a large number of tasks and multi-threading cannot withstand frequent creation and destruction? At this time, the thread pool comes out to solve the problem!
The thread pool is something similar to the Java string constant pool.
Using threads VS not using threads
When using a thread, just take a thread directly from the pool.
When a thread is not used, put this thread into the pool
Everyone knows that the process of finding a job is probably like this.
Submit resume
Written test
Interview
offer
After we get to the interview, there will be two situations.
If you pass, the company will call you to notify you and send you an offer
If you pass, the company will usually not tell you that you failed. , but did not tell you at all that you have not, because the company may put you in their "talent reserve pool".
Suppose the company is looking for 50 people, and during the fall recruitment period, it sends offers to 50 people. But in fact, only 35 people came to report. At this time, the remaining 15 people directly fish out 15 people from the talent reserve pool and make offers directly.
Maybe some time has passed at this time, and the company suddenly calls to inform you that you have been hired. Do you want to come? This operation is equivalent to using a thread directly from the pool.
This is to use the example of job hunting to describe what the thread pool probably means.
It is pointed out in the "Alibaba Java Development Manual" that thread resources must be provided through the thread pool, and thread creation is not allowed to be displayed in the application. On the one hand, the creation of threads is more standardized and the development can be reasonably controlled. The number of threads; on the other hand, the detailed management of threads is handed over to the thread pool, which optimizes resource overhead.
The "ThreadPoolExecutor" class is a set of classes provided by the Java standard library for using thread pools.
ThreadPoolExecutor has four construction methods. Each contains different parameters and is used in different scenarios.
We will introduce the construction method with the most parameters.
ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor ( int corePoolSize, int maximumPoolSize , long keepAliveTime , TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler )
1.corePoolSize The number of core threads
2.maximumPoolSize The maximum number of threads
For the number of core threads and the maximum number of threads may not be I understand exactly what it does. Here is an example of an employee going to work.
The number of core threads is the official employees of the company, allowing them to fish for a while. If you are discovered, you will not be fired. (Equivalent to the 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 and temporary workers in the company, but the temporary workers here have reached a certain level. It's time to be fired. (Equivalent to the threads in the thread pool being destroyed)
3.keepAliveTime describes how long temporary workers can fish.
4.unit is a unit of time, which is the unit of keepAliveTime.
5.workQueue blocking queue organizes the tasks to be performed by the thread pool
6.threadFactory thread creation method, use this parameter to set the creation method of different threads
7.RejectedExecutionHandler handler rejection strategy. When the task queue is full and a new task comes, what should we do at this time?
(1): The latest task is no longer required
(2): The oldest task is no longer required
(3): Blocking waiting
( 4) Open pendulum: throw an exception
Because ThreadPoolExecutor is more complicated to use, it has up to 7 parameters. The standard library provides programmers with a set of additional 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 thread pool with a variable number
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 can set the delay time.
ExecutorService Service4 = Executors.newScheduledThreadPool (20);
模拟实现一个线程池的核心操作: .:将任务加到线程池中--submit。 .:使用Worker类描述一个工作线程,Runnable来描述一个任务。 .:创建一个BlockingQueue阻塞队列组织所有任务。 .:每个Worker要做的事情就是不停的从阻塞队列里获取任务并执行。 .:指定线程池中的线程最大数目,如果超过这个数目就不要再继续创建线程了。
Code implementation:
我们创建一个线程池并让它不停的创建进程打印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: 模拟实现线程池的使用 */ public class ThreadDemo0327_2 { public static void main (String[] args) throws IOException, InterruptedException { ThreadPoll threadPoll=new ThreadPoll (); for (int i = 0 ; i <10 ; i++) { threadPoll.submit (new Runnable () { @Override public void run () { System.out.println ("hello"); } }); } } } class Worker extends Thread{ public BlockingQueue<Runnable> queue=null; public Worker(BlockingQueue<Runnable> queue){ this.queue=queue; } @Override public void run () { //工作线程的具体逻辑 //需要从阻塞队列中取任务. while (true){ try { Runnable command=queue.take (); //通过run来执行具体任务 command.run (); }catch (InterruptedException e){ e.printStackTrace (); } } } } class ThreadPoll{ //包含一个阻塞队列,用来组织任务 public BlockingQueue<Runnable> queue=new LinkedBlockingQueue<> (); //这个list就用来存放当前的工作线程. public List<Thread> works=new ArrayList<> (); public int MAX_WORKER_COUNT=10; //通过这个方法,把任务加入到线程池中 //submit不光可以把任务放到阻塞队列中,也可以负责创建线程 public void submit(Runnable command) throws IOException, InterruptedException { if(works.size ()<MAX_WORKER_COUNT){ //如果当前工作线程的数量不足线程数目上线,就创建出新的线程 //工作线程就专门找一个类完成 //worker内部要哦能够取到队列的内容,就要把这个队列实例通过worker的构造方法传过去 Worker worker=new Worker (queue); worker.start (); works.add (worker); } queue.put (command); } }
运行效果:
可以看到,打印了10个hello。
The above is the detailed content of How to implement the construction method of Java thread pool. For more information, please follow other related articles on the PHP Chinese website!