Do you know, "When the number of tasks exceeds the number of core threads in the thread pool, how to make it not enter the queue, but directly enable the maximum number of threads"?
Hi, my name is Mic, a Java programmer who has been working for 14 years.
Just now this question was encountered by a fan who had worked for 5 years recently when he went to an Internet company for an interview.
Regarding this question, I organized the master's answers into a 15W interview document.
You can private message me to get it
Check out the experts' answers below
master
When we submit a task to the thread pool, it works in four steps.
- The first step is to warm up the core thread
- The second step is to add the task to the blocking queue
- The third step, if adding to the blocking queue fails, create a non-core thread to increase processing efficiency
- The fourth step, if the number of non-core threads reaches the threshold, trigger the rejection policy
Therefore, if you want this task not to enter the queue, you only need to affect the execution logic of the second step.
In the constructor provided by the thread pool in Java, there is a parameter that can modify the type of the blocking queue.
Among them, there is a blocking queue called SynchronousQueue, which cannot store any elements.
Its characteristic is that every time a task is produced, a consumer must be assigned to process it, otherwise the producer will be blocked.
Based on this feature, just replace the blocking queue of the thread pool with SynchronousQueue.
It can avoid the task from entering the blocking queue, but directly start the maximum number of threads to process the task.
Summarize
The perspective of this question is actually quite interesting.
It can screen out many students who rely on the back test questions to prepare for the interview.
As long as you understand the working principle of the thread pool and read the source code, you can easily answer it.
Remember to like and subscribe! ! !
Copyright notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated. Please indicate the source forMic带你学架构
!
If this article is helpful to you, please help to follow and like, your persistence is the driving force for my continuous creation. Welcome to follow the WeChat public account of the same name to get more technical dry goods!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。