In a modern operating system, there is a very important concept - threads, almost all current popular operating systems support threads, threads from the concept of processes in the operating system, have their own virtual address space, data, data Sections and stacks, and each occupy different system resources (such as files, environment variables, etc.). Unlike this, threads cannot exist alone. It is attached to the process and can only be derived from the process. If a process is born out of two threads, the two threads share the global variables and code segments of this process, but each thread has their own stacks, so they have their own local variables, threads are still in the UNIX system Further divided into user-level threads (managed from process from process) and system-level threads (managed by the operating system's scheduler). Since there is a process, why do you want to make a thread concept? Because you create a small system resource for some small applications than to create a new process, you may not feel this, but use threads for applications that are particularly available in concurrent processes. A better performance is achieved than the usage process, thereby reducing the burden on the operating system. In addition, the thread sharing creates a global variable of its process, so communication programming between threads will be more simple, fully abandoned the IPC programming of the traditional processes, while using shared global variables to make thread interval communication. With this concept, we will enter the topic below, let's take a look at how the thread pool is? In fact, the principle of thread pool is simple. It is similar to the concept of buffer in the operating system. Its process is as follows: first start a number of threads and let these threads are in sleep state, when the client has a new request, Wake the thread in the thread pool, let it handle this request for the client. After processing this request, the thread is in sleep. Maybe you may ask: Why do you want to get so trouble, if you have a new request, I will create a new thread is not finished? This may be a good way, because it can make your code relatively easy, but you ignore an important issue - performance! Take my own unit, my unit is a bank network center in the provincial data, the peak period, the client requests and exceeds 100, if each client is requested to create a new thread, That consumable CPU time and memory will be amazing, if you use a thread pool with 200 threads, it will save a lot of system resources, making more CPU time and memory to handle actual commercial applications, and Not frequent thread creation and destruction. Since everything understands, then we start to implement a real thread pool, thread programming can be implemented, such as C, C , Java, etc., but different operating systems provide different thread API interfaces, In order to let you know the principle of thread pool, I use the Java language to implement it, because Java languages are a cross-platform language, so you don't have to use different operating systems. Unable to compile this program is distressed, as long as you have a version of JDK1.2 or more, you can correctly compile the run. In addition, the Java language itself has a built-in thread object, and the Java language is a complete image object, so you can make you more clearly understand the principle of thread pool, if you pay attention to see the title of this article, you will find the code of the sample program. Only about 100 lines.
This sample program consists of three classes, the first is the TestthreadPool class, which is a test program that simulates the client's request. When you run it, the system will display the initialization information of the thread pool first, then prompt you from the keyboard Enter the string and press the Enter key, then you will discover the display information on the screen, tell you that a thread is handling your request, if you enter a row string, then you will find the thread pool Constantly there is a wake-up to handle your request, in this case, I created a thread pool with 10 threads. If there is no available thread in the thread pool, the system will prompt your corresponding warning information, but if you Wait a moment, then you will find that the landing of the land will prompt the thread to enter the sleep state, then you can send a new request. The second class is the ThreadPoolManager class, as the name suggests, it is a class for managing the thread pool, and its main responsibility is to initialize the thread pool, and assign different threads for the client's request. If the thread pool is full, it Will send you a warning message. The last class is a SimpleThread class. It is a subclass of the Thread class. It tries to process the client's request, and SimpleTHread is in sleep state when the sample program is initialized, but if it accepts the scheduling information sent by the ThreadpoolManager class, Woke yourself and process the request. First let's take a look at the source code of the TestthreadPool class:
//TestThreadPool.java1 import java.io *;. 234 public class TestThreadPool5 {6 public static void main (String [] args) 7 {8 try {9 BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); 10 String S; 11 ThreadpoolManager Manager = New ThreadPoolManager (10); 12 While ((s = br.readline ())! = Null) 13 {14 manager.process (s); 15} 16} catch (ooException e) {} 17} 18}
Since this test program uses an input input class, the first line introduces the Java's basic IO processing package. In Chapter 11, we created a class named Manager, which passed a value for the ThreadpoolManager class constructor. Tell the THREADPOOLMANAGER Class: I want a pool with 10 threads, create one! Chapter 12 to 15 lines are an unlimited loop, which is used to wait for the user to type, and save the typed string in the S variable and call the THREADPOOLMANAGER class's Process method to process this request. Below we will follow the ThreadpoolManager class, the following is its source code:
//ThreadPoolManager.java1 import java.util *;. 234 class ThreadPoolManager5 {67 private int maxThread; 8 public Vector vector; 9 public void setMaxThread (int threadCount) 10 {11 maxThread = threadCount; 12} 1314 public ThreadPoolManager (int threadCount) 15 {16 setMaxthread (ThreadCount); 17 System.out.Println ("Starting Thread Pool ..."); 18 Vector = new vector (); 19 for (int i = 1; i <= 10; i ) 20 { 21 SimpleThread Thread = New SimpleThread (i); 22 Vector.Addelement (Thread); 23 Thread.Start (); 24} 25} 2627 Public Void Process (String Argument) 28 {29 INT i; 30 for (i = 0; i Let's pay attention to this class constructor and then look at its process () method. Lines 16-24 are its constructor, first it gives the ThreadpoolManager class Maxthread MaxThread, MaxThread represents the number of maximum threads in the thread pool. Chapter 18, first initializing a array vector, which is used to store all the SimpleThread classes, which fully reflects the superiority and artisticity of the Java language: If you use C language, you must write at least 100 rows of code to complete the vector. Function, and C language arrays can only hold the basic data type of type uniform, and cannot accommodate objects. Ok, gossip less, the loop of the 19-24 line completes this feature: first create a new SimpleTHRead class, then put it into the vector, finally use thread.start () to launch this thread, why Use the start () method to start the thread? Because this is specified in the Java language. If you are not, then these threads will never be activated, causing this example program that cannot be run at all. Let's take a look at the Process () method, the loop of the 30-40 row sequentially select the SimpleThread thread from the Vector array and check if it is active (so-called activation state means whether the client is processed), if If you are active, then continue to find the next item of the Vector array. If all the threads in the Vector array are active, it will print out a message, prompting the user to try again. On the contrary, if you find a sleep thread, the 35-38 row will process this. First tell which thread is to process this request, then forward the client's request, the string argument to the SimpleThread class. The setargument () method is handled, and the SIMPLETHREAD class's setRunning () method is called to wake up the current thread to process the client request. Maybe you also have some wake-up for the setrunning () method, then we will enter the last class now: SimpleThread class, its source code is as follows: //SimpleThread.java1 class SimpleThread extends Thread2 {3 private boolean runningFlag; 4 private String argument; 5 public boolean isRunning () 6 {7 return runningFlag; 8} 9 public synchronized void setRunning (boolean flag) 10 {11 runningFlag = flag; 12 IF (Flag) 13 this.notify (); 14} 1516 public string getargument () 17 {18 returnomegument; 19} 20 public void setargument (string string) 21 {22 argument = string; 23} 2425 public simplethread (int threenumber) 26 {27 runningflag = false; 28 System.Out.println ("Thread" ThreadNumber "Started."); 29} 3031 public synchronized void Run () 32 {33 try {34 While (TRUE) 35 {36 if (! Runningflag) 37 {38 this.wait (); 39} 40 else41 {42 system.out.println ("processing" getargument () "... done."); 43 SLEEP (5000) 44 System.out.Println ("Thread Is Sleeping ..."); 45 Strunning (false); 46} 47} 48} catch (interruptedException e) {49 system.out.println ("interrupt"); 50} 51} // end of run () 52} // end of class simplethread