1, Thread pool introduction:
Multithreading technology mainly solves the problem of multiple threads in the processor unit, which can significantly reduce the idle time of the processor unit and increase the throughput capacity of the processor unit.
assume that a server takes a task to complete: T1 creates the thread time, T2 the time to execute the task in the thread, T3 destroys the threading time.
if: T1 + T3 is larger than T2, you can use a thread pool to improve server performance.
A thread pool consists of the following four basic components:
1, Thread pool Manager (ThreadPool): Used to create and manage thread pools, including creating a thread pool, destroying the thread pool, adding new tasks;
2, worker thread (poolworker): Thread pool threads, in the absence of a task in the waiting state, you can cycle the execution of tasks;
3, Mission Interface (Task): the interface that each task must implement, For the execution of the task, it mainly stipulates the entrance of the task, the finishing work after completion of the task, the execution status of the task, etc.
4, Task queue (Taskqueue): Used to store tasks that are not processed. Provides a buffering mechanism.
Thread pooling technology is a technique that focuses on how to shorten or adjust t1,t3 time to improve the performance of server programs. It t1,t3 the start and end of the server program, or some idle time period, so that there is no t1,t3 overhead when the server program processes the client request.
The thread pool not only adjusts the time period generated by the T1,T3, but it also significantly reduces the number of threads created, looking at an example:
Suppose a server handles 5,000 requests a day, and each request requires a separate thread to complete. The number of threads in a thread pool is generally fixed, so the total number of threads does not exceed the number of threads in the thread pool, and the total number of threads is 5000 if the server does not use the thread pool to process these requests. The general thread pool size is far less than 5000. Therefore, server programs that utilize the thread pool do not waste time processing requests in order to create 5000, thereby increasing efficiency.
Instead of implementing the task interface in the code implementation, the Runnable object is added to the thread pool manager (ThreadPool), and the rest is done by the thread pool Manager (ThreadPool).
PackageMine.util.thread; Importjava.util.LinkedList; Importjava.util.List; /*** thread pool class, threading Manager: Create threads, perform tasks, destroy threads, get thread basic information*/ Public Final classThreadPool {//the number of default threads in the thread pool is 5 Private Static intWorker_num = 5; //Worker Threads Privateworkthread[] workthrads; //Tasks not processed Private Static volatile intFinished_task = 0; //task queue, as a buffer, the list thread is unsafe PrivateList<runnable> Taskqueue =NewLinkedlist<runnable>(); Private StaticThreadPool ThreadPool; //Create a thread pool with the number of default threads PrivateThreadPool () { This(5); } //Create a thread pool, worker_num the number of worker threads in the thread pools PrivateThreadPool (intworker_num) {Threadpool.worker_num=Worker_num; Workthrads=NewWorkthread[worker_num]; for(inti = 0; i < Worker_num; i++) {Workthrads[i]=NewWorkthread (); Workthrads[i].start ();//to open a thread in a thread pool } } //single mode, get a thread pool with the number of default threads Public StaticThreadPool Getthreadpool () {returnGetthreadpool (Threadpool.worker_num); } //single mode, get a thread pool with a specified number of threads, Worker_num (>0) is the number of worker threads//worker_num<=0 Create default number of worker threads Public StaticThreadPool Getthreadpool (intworker_num1) { if(worker_num1 <= 0) Worker_num1=Threadpool.worker_num; if(ThreadPool = =NULL) ThreadPool=NewThreadPool (WORKER_NUM1); returnThreadPool; } //To perform a task, it is simply to join the task queue and when to execute the thread pool manager perception Public voidExecute (Runnable Task) {synchronized(taskqueue) {taskqueue.add (Task); Taskqueue.notify (); } } //To execute a task in bulk, it is simply to join the task queue and when to execute the thread pool manager perception Public voidExecute (runnable[] task) {synchronized(taskqueue) { for(Runnable t:task) taskqueue.add (t); Taskqueue.notify (); } } //To execute a task in bulk, it is simply to join the task queue and when to execute the thread pool manager perception Public voidExecute (list<runnable>Task) { synchronized(taskqueue) { for(Runnable t:task) taskqueue.add (t); Taskqueue.notify (); } } //destroys the thread pool, which ensures that all threads are destroyed if all tasks are completed, otherwise it is not destroyed until the task is completed Public voiddestroy () { while(!taskqueue.isempty ()) {//If there's still a job to do, just go to sleep. Try{Thread.Sleep (10); } Catch(interruptedexception e) {e.printstacktrace (); } } //worker thread stops working and is set to null for(inti = 0; i < Worker_num; i++) {workthrads[i].stopworker (); Workthrads[i]=NULL; } ThreadPool=NULL; Taskqueue.clear ();//Empty Task Queue } //returns the number of worker threads Public intGetworkthreadnumber () {returnWorker_num; } //returns the number of completed tasks, where the completion is only the number of tasks out of the task queue, perhaps the task is not actually completed Public intGetfinishedtasknumber () {returnFinished_task; } //returns the length of the task queue, which is the number of tasks that have not yet been processed Public intGetwaittasknumber () {returntaskqueue.size (); } //override tostring Method, return thread pool information: number of worker threads and number of completed tasks@Override PublicString toString () {return"Workthread Number:" + Worker_num + "finished task number:" + finished_task + "Wait task number:" +Getwaittasknumber (); } /*** Inner class, worker thread*/ Private classWorkthreadextendsThread {//whether the worker thread is valid to end the worker thread Private BooleanIsRunning =true; /** The key is that if the task queue is not empty, then the task execution is removed, and if the task queue is empty, wait*/@Override Public voidrun () {Runnable R=NULL; while(isrunning) {//Note that if the thread is invalid, the Run method ends naturally, and the thread is useless. synchronized(taskqueue) { while(IsRunning && taskqueue.isempty ()) {//queue is empty Try{taskqueue.wait (20); } Catch(interruptedexception e) {e.printstacktrace (); } } if(!Taskqueue.isempty ()) R= Taskqueue.remove (0);//Remove Task } if(r! =NULL) {r.run ();//Perform Tasks} finished_task++; R=NULL; } } //stop working and let the thread run through the Run method naturally ends Public voidStopworker () {isrunning=false; } } }
Test code
PackageMine.util.thread; //Test thread pool Public classTestthreadpool { Public Static voidMain (string[] args) {//Create a thread pool of 3 threadsThreadPool t = Threadpool.getthreadpool (3); T.execute (NewRunnable[] {NewTask (),NewTask (),NewTask ()}); T.execute (NewRunnable[] {NewTask (),NewTask (),NewTask ()}); System.out.println (t); T.destroy ();//all threads are executed before DestorySystem.out.println (t); } //Task Class Static classTaskImplementsRunnable {Private Static volatile inti = 1; @Override Public voidRun () {//Perform TasksSYSTEM.OUT.PRINTLN ("task" + (i++) + "Finish"); } } }
2. Introduction to the thread pool provided in the Java class Library:
The thread pool provided by Java is more powerful, and it is believed that understanding how the thread pool works will not be unfamiliar to the thread pool in the class library.
The implementation principle of thread pool