Reprint, please pay attention to the source: blog.csdn.net/fengye45454…

A few days ago, the company interview, asked a lot of thread pool questions, because is also a rookie was not familiar with the thread pool, coupled with a nervous head a tight, GG, after it can be described as deep hate pain, decided to thread pool side of a good sort.

The benefits of thread pools

What is a thread pool? What is a thread pool? What is a thread pool? So let me clarify the benefits of cleaning up thread pools.

Thread pool reuse

The overhead of thread creation and destruction is huge, and the reuse of the thread pool greatly reduces this overhead. Of course, with so much less memory consumption, thread execution speed is also greatly improved.

2. Control the number of concurrent threads in the pool

Beginners may be unfamiliar with the word concurrency, so I also combine baidu encyclopedia and bibi to get the best explanation, and never forget that concurrency can be different from parallelism.

Concurrency: when more than one program is in between execution and completion in a certain period of time; But only one program is running at a time. Brainstorming: The mother eagle feeds her baby eagles. The baby eagles have a lot of food, but the eagle has only one mouth. She needs to feed them one by one.

Parallelism: Each program executes at its own independent asynchronous speed for a certain period of time, without interference from each other. Brainstorm: It’s as if the mother eagle decided that feeding was too much work and hired a nanny for each chick, so that at one point in time, each chick could eat at the same time, without interfering with each other.

Back to the thread pool, controlling the number of concurrent threads in the thread pool can effectively prevent a large number of thread pools from competing for CPU resources and causing congestion. Brainstorming: or take the example of the eagle, the mother is only one, so one by one to feed down, some hungry young eagle can not wait to break the rules, rob in front of the front feeding of the young eagle, and the front of the young eagle is not a soft meal, so the fight, chaos. Eagle angry, so not sensible, who also don’t eat, so caused the last who also have no food to eat the situation.

3. Thread pools can manage threads

Thread pool can provide timing, periodic, single thread, concurrency control and other functions. For example, the ScheduledThreadPool thread pool is used to execute tasks every N seconds after S seconds.

Detail of thread pool

Recommended blog: blog.csdn.net/seu_calvin/…

Surely after reading the above blog, everyone is full of praise, but maybe some partners still can not remember, there are small partners feel so disgusting ah, how are the toilet what ah! Ha ha, don’t worry, I’ll give you an easy way to remember.

Let’s start with the constructor with the most arguments, mainly analyzing those annoying arguments.

1, the ThreadPoolExecutor

public ThreadPoolExecutor(int corePoolSize,  
                              int maximumPoolSize,  
                              long keepAliveTime,  
                              TimeUnit unit,  
                              BlockingQueue<Runnable> workQueue,  
                              ThreadFactory threadFactory,  
                              RejectedExecutionHandler handler) Copy the code


Here are the 7 parameters (we use more of the 5 parameter constructor in development), OK, let’s see what the 7 parameters mean:

CorePoolSize Specifies the number of core threads in the thread pool

MaximumPoolSize Specifies the maximum number of threads in the thread pool

KeepAliveTime Timeout period of a non-core thread. When the idle time of a non-core thread exceeds keepAliveTime, the thread is reclaimed. If the allowCoreThreadTimeOut property of ThreadPoolExecutor is set to true, this parameter also represents the timeout duration of the core thread

Unit Unit of the third parameter, including nanosecond, microsecond, millisecond, second, minute, hour, day, etc

WorkQueue A queue of tasks in a thread pool. This queue is used to store tasks that have been submitted but not yet executed. The tasks stored here are submitted by the Execute method of ThreadPoolExecutor.

ThreadFactory provides the ability to create new threads for the thread pool, which we generally use as the default

Handler reject strategy, when there is no thread when performing a new task (usually because the number of threads in thread pool has reached maximum number or caused by thread pool closed), by default, when a thread pool is unable to process the new thread, throws a RejectedExecutionException.

emmmmm…. See so many annoying concepts, is there a big nod, I am a big head anyway.

The most commonly used parameters are corePoolSize, maximumPoolSize, keepAliveTime, Unit, and workQueue. CorePoolSize, maximumPoolSize and workQueue

MaximumPoolSize = corePoolSize + noCorePoolSize;

(1) When currentSize<corePoolSize, start a core thread and execute the task.

(2) If currentSize>=corePoolSize and the workQueue is not full, the added task will be added to the workQueue for execution.

(3) If the workQueue is full but currentSize<maximumPoolSize, it will open immediately

Start a non-core thread to execute the task.

(4) If currentSize>=corePoolSize, workQueue is full, and currentSize>maximumPoolSize, a RejectExecutionExpection exception will be raised by default.

What currentSize, corePoolSize, maximumPoolSize, workQueue ratios than to than is confused, ha ha, I for an example of grill to everybody understand more quickly.

Summer, very hot, so many barbecue restaurants will also decorate seats outside, divided into indoor and outdoor two places to eat barbecue. (Indoor air conditioning TV, and indoor barbecue is more favorable than outdoor, and it is pouring rain outside, so customers will choose indoor first)

CorePoolSize (indoor seats), cuurentPoolSize (current number of customers in the barbecue restaurant), maximumPoolSize (indoor + outdoor + all seats in the waiting room), workQueue(waiting room specially set up for customers in the barbecue restaurant)

(1) When the number of people in the barbecue restaurant is small, there are many indoor locations, and everyone is happy and happy to sit in the room eating barbecue and watching the World Cup.

(2), business is good, the indoor barbecue restaurant is full, people do not want to eat outside, so they stay in the waiting room, the waiting room is not full.

(3), the business is booming, the room and waiting hall are full, but the customers are too hungry, the rest of the people have no choice but to eat barbecue in the rain, ha ha, so poor.

(4), the business is overflowing, indoor, outdoor, hou hall room are sitting empty seats, in the customer come directly away.

I’m still a stranger to workQueue.

Recommended blog:http://blog.csdn.net/u012702547/article/details/52259529

2, other thread pool notation

The remaining four main thread pools are explained in detail in my recommended blog, but I’m not going to go into them all here. Instead, I’m going to share with you a very easy way to remember these four thread pools so that you can think about them when you’re writing code and interviewing.

(1) FixedThreadPool:

Fixed means Fixed in Chinese. Put together to explain a fixed thread pool, or more generally, a thread pool with a fixed number of threads. CorePoolSize =maximumPoolSize and keepAliveTime = 0, suitable for stable threads.

(2) SingleThreadPool:

Single. Singlethreadpools are mathematically subsets of FixedThreadPools. Singlethreadpools are a subset of fixedThreadPools. CorePoolSize =maximumPoolSize=1 and keepAliveTime = 0, suitable for thread synchronization.

(3) CachedThreadPool:

Cached means stored in Chinese. CorePoolSize =0, maximumPoolSize= integer. MAX_VALUE(2^32-1)

(4) ScheduledThreadPool:

Scheduled Is the Chinese word for Scheduled. Thread pools that combine to explain schedules, as the name implies, involve time as well as planning. So ScheduledThreadPool is a thread pool with the ability to execute tasks at regular intervals.

Thread pool singleton

Let me stretch. It’s time to get to the main point of this chapter. Before that, let’s take a look at some basic semantics.

What is a singleton? Ahem.

1, the singleton

The Singleton Pattern is one of the simplest design patterns in Java. This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its unique objects directly, without instantiating the objects of the class.

Matters needing attention:

  • 1. A singleton class can have only one instance.
  • 2. A singleton class must create its own unique instance.
  • 3. The singleton class must provide this instance to all other objects.

Recommendation: www.runoob.com/design-patt…

2. Thread pool singleton

So the question is, I’m pretty good with thread pools. I create one when I use it and leave it when I don’t, so why do I design thread pools as singletons? It’s up to you to see where you’re applying thread pools. In general, you only need a single thread pool for the entire system. Multiple threads share a thread pool. You don’t need to create a thread pool for every thread you create.

Without further ado, let’s look at how to design thread pools as singletons. Cut to the code

Create a FixedThreadPool ThreadPool. (remember that the constructor is private and cannot be instantiated by another class.)

private ThreadPool(int corepoolsize, int maximumpoolsize, long keepalivetime){ this.corepoolsize = corepoolsize; this.maximumpoolsize = maximumpoolsize; this.keepalivetime = keepalivetime; } public void executor(Runnable runnable){ if (runnable == null){ return; } if (mexecutor == null){mexecutor = new ThreadPoolExecutor(corePoolsize, maximumpoolsize, Timeunit.milliseconds, // new LinkedBlockingDeque<Runnable>(), / / thread queue Executors. DefaultThreadFactory (), / / thread factory new ThreadPoolExecutor AbortPolicy () / / queue is full, and the number of the current thread has exceeded the maximum number of threads of exception handling strategy); } mexecutor.execute(runnable); }Copy the code





We then instantiate the inner class of ThreadPool to implement the singleton

Public static ThreadPool getThreadPool() {if (mThreadPool == null) {synchronized (threadManager.class) {  if (mThreadPool == null) { int cpuNum = Runtime.getRuntime().availableProcessors(); Int threadNum = cpuNum * 2 + 1; MThreadPool = new ThreadPool(threadNum, threadNum, 0L); } } } return mThreadPool; }Copy the code


The Demo address:Download.csdn.net/download/fe…

A novice, if there is anything wrong, please point out. Your encouragement is the biggest power of my writing!