This article introduces to you about the interview may encounter the problem of thread pool, has a certain reference value, the need for friends can refer to.
Objective
We often encounter multi-threading and thread pool problems in the interview, how to answer? Today we're going to learn about the thread pool in Java.
What is a thread pool
A thread pool is a collection of threads that are created during the initialization of a multithreaded application, and then reused when new tasks are needed instead of creating a new thread. The number of threads in the thread pool usually depends entirely on the amount of available memory and the requirements of the application. However, it is possible to increase the number of available threads. Each thread in the thread pool has a task assigned to it, and once the task is completed, the thread goes back to the pool and waits for the next assignment.
plainly, it is a thread collection that executes multiple threads for an application .
Why do I need a thread pool?
Using the thread pool, I've solved the problem at the moment:
Save time and resources by using the thread pool to get multiple cover pages in a video
Background server does not support multiple image uploads, using the thread pool to upload multiple images, thus reducing the time to upload
As follows:
Before uploading: 9 images take at least 3 seconds, and with the thread pool optimized, 9 images take 1 seconds.
It is necessary to use threads in multithreaded applications for several reasons:
1. Reduces the number of times a thread is created and destroyed, and each worker thread can be reused to perform multiple tasks.
2. You can adjust the number of threads in the thread pool according to the endurance of the system, prevent the server from being exhausted because it consumes too much memory (approximately 1MB of memory per thread, the more threads open, the more memory is consumed and the last crashes).
The thread pool improves response time for an application. Because threads in the thread pool are ready and waiting for tasks to be assigned, the application can be used directly instead of creating a new thread.
The thread pool saves the CLR the overhead of creating a full thread for each short life cycle task and can reclaim resources after the task is completed.
The thread pool optimizes threading time slices based on the processes currently running in the system.
The thread pool allows us to open multiple tasks without setting properties for each thread.
The thread pool allows us to pass an object reference containing state information for the program parameters of the task being executed.
The thread pool can be used to resolve the limit on the maximum number of threads that handle a particular request.
To appease a multi-year-old hair hair
The role of the thread pool:
The thread pool function 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 performance; less waste of system resources, more caused by the system congestion efficiency is not high. Use the thread pool to control the number of threads and other threads to wait. A task is completed, and then the first task from the queue is executed. If there is no waiting process in the queue, this resource of the thread pool is waiting. When a new task needs to run, it can start running if there are waiting worker threads in the thread pool, otherwise enter the wait queue.
The drawbacks of single thread
As an example,
New Thread (New Runnable () {@Overridepublic void run () { papapayourgridfriend ();}}). Start ();
Important thing to say three times!!!
If you're still performing an asynchronous task with the new thread, so you're out!
If you're still performing an asynchronous task with the new thread, so you're out!
If you're still performing an asynchronous task with the new thread, so you're out!
The disadvantages are as follows:
A. Each new thread creates a poor performance for the newly created object.
B. Lack of unified management of threads, the possibility of unlimited new threads, competing with each other, and potentially consuming excessive system resources can lead to freezing or oom.
C. Lack of additional functionality, such as timed execution, periodic execution, and thread interruption.
Java thread Pool
1. Newsinglethreadexecutor
Creates a single threaded pool of threads. This thread pool has only one thread at work, which is equivalent to single-threaded serial execution of all tasks. If this unique thread ends because of an exception, a new thread will replace it. This thread pool guarantees that the order in which all tasks are executed is performed in the order in which the tasks are submitted.
2.newFixedThreadPool
Creates a fixed-size thread pool. Each time a task is committed, a thread is created until the thread reaches the maximum size of the threads pool. Once the maximum size of the thread pool is reached, the thread pool will be replenished with a new thread if it ends up executing an exception.
3. Newcachedthreadpool
Creates a cacheable pool of threads. If the size of the thread pool exceeds the thread that is required to process the task,
Then a partially idle (60 second non-performing) thread is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does not limit the size of the thread pool, and the thread pool size 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 schedule and periodically perform tasks.
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 () {//cyclic output F or (int i = 0; i < i++) {System.out.print ("A" +i+ "\ t"); }}} Private class MyTask2 implements runnable{@Override public void Run () {//try {//Thread.Sleep (+);//} catch (Interruptedexception e) {//E.printstacktrace ();//}//Loop output for (int i = 0; i < i++) { System.out.print ("B" +i+ "T"); }}} Private class MyTask3 implements runnable{@Override public void Run () {//Loop output Out for (int i = 0; i < i++) {System.out.print ("C" +i+ "\ t"); } } }
Scheduledexecutorservice
Newfixedthreadpool
Newcachedthreadpool
The benefits of the four thread pools provided by new Thread,java are:
A. Reusing existing threads, reducing the cost of object creation, extinction, and performance.
B. Can effectively control the maximum number of concurrent threads, improve the utilization of system resources, while avoiding excessive resource competition, avoid clogging.
C. Provide functions such as timed execution, periodic execution, single-threaded, concurrency control, etc.
Line Chengchijin is too good to use, if you manage threads through thread pooling in your project, you will find many advantages!
Read more
20+ a great Android Open source project
2018 Android Face test with answer-for advanced (bottom) a complete Android studio build flutter tutorial [] (Http://mp.weixin.qq.com/s?__b ...
Learn more about thread break methods in Java summary of experience
Why a child thread cannot update the UI thread
Believe in yourself, there is nothing to do, only unexpected