preface
We often come across the question of multi-threading and thread pooling in the interview, how to answer it? Today we are going to look at thread pools in Java.
What is a thread pool
Thread pooling is the process of creating a collection of threads during the initialization of a multithreaded application, and then reusing these threads when new tasks are needed instead of creating a new thread. The number of threads in a thread pool usually depends entirely on the amount of memory available and the requirements of the application. However, it is possible to increase the number of threads available. Each thread in the thread pool is assigned a task, and once the task has been completed, the thread returns to the pool and waits for the next assignment.
Basically, a collection of threads that execute multiple threads for an application.
Why do we need thread pools?
Using thread pools, I have solved the following problems so far:
- Save some time and resources by using thread pools to get multiple covers in a video
- The background server does not support multiple picture uploads. The thread pool is used to upload multiple pictures, thus reducing the upload time
The renderings are as follows:
Before uploading: at least 3 seconds for 9 images, 1 second for 9 images after thread pool optimization.
Using threads in multithreaded applications is necessary for several reasons:
-
1. The number of threads created and destroyed is reduced. Each worker thread can be reused to perform multiple tasks.
-
2. According to the capacity of the system, adjust the number of threads in the thread pool to prevent excessive memory consumption, and the server tired down (each thread needs about 1MB memory, the more the thread opens, the more memory consumption, and finally crash).
-
- Thread pooling improves the response time of an application. Because threads in the thread pool are ready and waiting to be assigned tasks, applications can use them directly without creating a new thread.
-
- Thread pooling saves the CLR the overhead of creating a full thread for each short-life task and can reclaim resources after the task completes.
-
- Thread pools optimize thread time slices based on the processes currently running on the system.
-
- Thread pooling allows us to start multiple tasks without setting properties for each thread.
-
- Thread pooling allows us to pass an object reference containing state information for the program parameters of the task being performed.
-
- Thread pools can be used to solve the problem of limiting the maximum number of threads that can process a particular request.
Soothe the older fafa
Thread pools are used for:
The purpose of a thread pool is to limit the number of threads executing in the system. According to the environment of the system, the number of threads can be set automatically or manually to achieve the best effect of operation; Less waste of system resources, more congested system efficiency is not high. Use thread pools to control the number of threads, and other threads queue up to wait. After a task is executed, it takes the first task from the queue and starts to execute it. If there are no waiting processes in the queue, this resource in the thread pool is waiting. When a new task needs to run, if there are waiting worker threads in the thread pool, it can start running. Otherwise, the queue is entered.
Disadvantages of single threading
For example
new Thread(new Runnable() {
@Override
public void run() {
paPaPaYourGridFriend();
}
}).start();
Copy the code
Important things say three times!!
If you are still executing an asynchronous task with a new Thread, you are Out! If you are still executing an asynchronous task with a new Thread, you are Out! If you are still executing an asynchronous task with a new Thread, you are Out!
The disadvantages are as follows:
- A. Poor performance of objects created by new Threads each time.
- B. Lack of unified management of threads, unlimited new threads may compete with each other, and may occupy too many system resources, resulting in crash or OOM.
- C. Lack of more functions, such as scheduled execution, periodic execution and thread interruption.
Java thread pool
1. newSingleThreadExecutor
Create a single thread pool. This thread pool has only one thread working, which is equivalent to a single thread executing all tasks in serial. If the unique thread terminates due to an exception, a new thread will replace it. This thread pool ensures that all tasks are executed in the order in which they were submitted.
2.newFixedThreadPool
Create a thread pool of fixed size. A thread is created each time a task is submitted until the thread reaches the maximum size of the thread pool. The size of the thread pool stays the same once it reaches its maximum size, and if a thread terminates due to execution exceptions, a new thread is added to the pool.
3. newCachedThreadPool
Create a cacheable thread pool. If the size of the thread pool exceeds the number of threads needed to process the task,
Some idle (60 seconds) threads are reclaimed, and as the number of tasks increases, the pool can intelligently add new threads to handle the task. This thread pool has no limit on the thread pool size, which is entirely dependent on the maximum thread size that the operating system (or JVM) can create.
4.newScheduledThreadPool
Create a thread pool of unlimited size. This thread pool supports the need to execute tasks regularly and periodically.
newSingleThreadExecutor
private void TextnewSingleThreadExecutor(){
ExecutorService pool = Executors. newSingleThreadExecutor();
MyTask1 task1 = new MyTask1();
MyTask2 task2 = new MyTask2();
MyTask3 task3 = new MyTask3();
// pool.execute(task1);
// pool.execute(task2);
// pool.execute(task3);
new Thread(task1).start();
new Thread(task2).start();
new Thread(task3).start();
}
private class MyTask1 implements Runnable{
@Override
public void run() {// loop outputfor(int i = 0; i < 100; i++)
{
System.out.print("A"+i+"\t");
}
}
}
private class MyTask2 implements Runnable{
@Override
public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); //} // loop outputfor(int i = 0; i < 100; i++)
{
System.out.print("B"+i+"\t");
}
}
}
private class MyTask3 implements Runnable{
@Override
public void run() {// loop outputfor(int i = 0; i < 100; i++)
{
System.out.print("C"+i+"\t"); }}}Copy the code
ScheduledExecutorService
newFixedThreadPool
newCachedThreadPool
The benefits of Java’s four Thread pools over New Threads are as follows:
- A. Reuse existing threads, reduce the overhead of object creation and death, and improve performance.
- B. Effectively controls the maximum number of concurrent threads, improves system resource usage, and avoids excessive resource competition and congestion.
- C. Provides functions such as scheduled execution, periodic execution, single thread, and concurrency control.
Thread pools are incredibly useful, and if you manage threads in a project through a thread pool, you’ll find many advantages!
To read more
20+ great Android open source projects
A complete tutorial on Building Flutter by Android Studio
In-depth understanding of JAVA thread interrupt method experience summary
Why can’t child threads update the UI thread
Believe in yourself, there is nothing impossible, only unexpected
It’s not just technology that’s gained here!