In the modern operating system, there is a very important concept--thread, almost all the current popular operating systems support threads, threads from the concept of the process in the operating system, the process has its own virtual address space and body segments, data segments and stacks, and each occupies a different system resources (such as files, environment variables, etc.). Unlike this, a thread cannot exist alone, it is attached to a process and can only be derived from a process. If a process derives two threads, the two threads share the global variables and code snippets of the process, but each thread has its own stack, so they have their own local variables, Threads are further divided into user-level threads (managed by processes themselves) and system-level threads (managed by the operating system's scheduler) in UNIX systems.
Now that you have a process, why do you want to propose the concept of threading? Because, compared to the creation of a new process, creating a thread will consume much less system resources and may not be felt for some small applications, but for applications that have a particularly heavy number of concurrent processes, threading can be more performance-intensive than using a process, thus reducing the burden on the operating system. In addition, the thread shares the global variables of the process that created it, so the communication programming between threads will be simpler, and it is entirely possible to discard the traditional IPC programming of interprocess communication and use shared global variables to communicate between threads.
With the above concept, we go to the bottom of the matter, to see what the thread pool is what? In fact, the thread pool principle is very simple, similar to the concept of a buffer in the operating system, its process is as follows: Start a number of threads first, and leave these threads asleep, and when the client has a new request, it wakes up a sleep thread in the thread pool to handle the client's request. When the request is processed, the thread is in a sleep state. Perhaps you might ask: why bother, if I create a new thread every time the client has a new request? This may be a good idea, because it makes it easier for you to write code, but you overlook an important problem-performance! Just take my unit, my unit is a provincial-level data-intensive Banking Network Center, the peak per second client request concurrency of more than 100, if the request for each client to create a new thread, the CPU time and memory will be amazing, if the use of a thread pool with 200 threads, That would save a lot of system resources, allowing more CPU time and memory to handle actual business applications rather than frequent thread creation and destruction.
Now that everything is clear, let's begin to implement a real thread pool, thread programming can be implemented in many languages, such as C, C + +, Java, and so on, but different operating systems provide different thread API interfaces, so that you can better understand the thread pool principle and avoid getting bogged down in cumbersome API calls. I use the Java language to implement it, because the Java language is a cross-platform language, so you do not have to use a different operating system to compile and run this program, as long as you have installed more than JDK1.2 version, can compile and run the program correctly. In addition, the Java language itself has a thread object built into it, and the Java language is completely object-like, so it gives you a clearer idea of how the thread pool works, and if you look at the title of this article, you'll find that the entire sample program has only about 100 lines of code.
This sample program consists of three classes, the first is the Testthreadpool class, it is a test program to simulate the client's request, when you run it, the system will first display the thread pool initialization information, and then prompts you to enter a string from the keyboard, and press ENTER, At this point you will notice that a message is displayed on the screen telling you that a line one thread is processing your request, if you quickly enter a line of string, you will find that threads in the thread pool are awakened to handle your request, and in this case I have created a thread pool with 10 threads, and if there are no threads in the thread pool, The system prompts you for a warning, but if you wait a moment, you will notice that the cable is on the way to sleep, and you can send a new request.
The second class, the Threadpoolmanager class, as the name suggests, is a class for managing the thread pool, its primary responsibility is to initialize the thread pool and assign different threads to the client's request, and if the thread pool is full, it will send a warning message to you.
The last class is the Simplethread class, which is a subclass of the thread class, that actually handles the client's request, Simplethread is asleep when the sample program initializes, But if it receives the dispatch information sent by the Threadpoolmanager class, it wakes itself up and processes the request.
First, let's look at the source code of the Testthreadpool class:
Testthreadpool.java
1 Import java.io.*;
2
3
4 public class Testthreadpool
5 {
6 public static void main (string[] args)
7 {
8 try{
9 BufferedReader br = new BufferedReader (new InputStreamReader (system.in));
Ten String S;
One Threadpoolmanager manager = new Threadpoolmanager (10);
while ((s = br.readline ())!= null)
13 {
Manager.process (s);
15}
}catch (IOException e) {}
17}
18}
Because this test program used the input input class, so line 1th imported Java's basic IO processing package, in line 11th, we created a class called manager that passed a parameter with a value of 10 to the constructor of the Threadpoolmanager class. Tell Threadpoolmanager class: I want a pool with 10 threads, create a bar for me! Line 12th to 15 is an infinite loop that waits for the user to type, saves the typed string in the S variable, and invokes the Threadpoolmanager class's process method to process the request.
Below we further trace to the Threadpoolmanager class, the following is its source code:
Threadpoolmanager.java
1 Import java.util.*;
2
3
4 Class Threadpoolmanager
5 {
6
7 private int maxthread;
8 public vector vector;
9 public void Setmaxthread (int threadcount)
10 {
One maxthread = ThreadCount;
12}
13
Public Threadpoolmanager (int threadcount)
15 {
Setmaxthread (ThreadCount);
SYSTEM.OUT.PRINTLN ("Starting thread pool ...");
vector = new vector ();
for (int i = 1; I <= i++)
20 {
Simplethread thread = new Simplethread (i);
Vector.addelement (thread);
Thread.Start ();
24}
25}
26
The public void process (String argument)
28 {
int i;
for (i = 0; i < vector.size (); i++)
31 {
Simplethread CurrentThread = (simplethread) vector.elementat (i);
if (!currentthread.isrunning ())
34 {
System.out.println ("Thread" + (i+1) + "is processing:" +
argument);
Currentthread.setargument (argument);
Panax Notoginseng currentthread.setrunning (true);
return;
39}
40}
if (i = = Vector.size ())
42 {
System.out.println ("Pool is full, try in another Time");
44}
45}
}//end of Class Threadpoolmanager
Let's focus on the constructor of this class and then look at its process () method. The 第16-24 row is its constructor, first it assigns a value to the Threadpoolmanager class's member variable Maxthread, Maxthread represents the number of threads that control the maximum thread in the thread pool. Line 18th Initializes an array vector, which is used to store all the Simplethread classes, which fully embodies the advantages and artistry of the Java language: If you use C, you must write at least 100 lines of code to complete the vector function, and the C-language array can only hold the type-uniform base data type and cannot accommodate objects. Well, less gossip, the 第19-24 loop completes the function of creating a new Simplethread class, then putting it in a vector and finally starting the thread with Thread.Start (), why start the thread with the start () method? Because that's what the Java language says, if you don't, these threads will never get activated, causing the sample program to run at all.
Let's take a look at the process () method, where the loop 第30-40 the line to select the Simplethread thread from the vector array and check whether it is active (the so-called activation State is whether the thread is processing the client's request), and if it is activated, Then continue to look for the next item in the vector array, and if all the threads in the vector array are active, it prints out a message prompting the user to try again later. Instead, if a sleeping thread is found, the 35–38 Guild handles it by telling the client which thread is going to handle the request, and then forwarding the client's request, the string argument, to the setargument of the Simplethread class () method to process the client request by invoking the Setrunning () method of the Simplethread class to wake the current thread.
Maybe you still don't understand how the setrunning () method wakes up the thread, so let's go to the last class now: Simplethread class, which has the following source code:
Simplethread.java
1 class Simplethread extends Thread
2 {
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 {
One runningflag = Flag;
if (flag)
This.notify ();
14}
15
Public String getargument ()
17 {
return this.argument;
19}
public void Setargument (string string)
21 {
argument = string;
23}
24
Simplethread public (int threadnumber)
26 {
Runningflag = false;
SYSTEM.OUT.PRINTLN ("thread" + Threadnumber + "started.");
29}
30
To public synchronized void run ()
32 {
try{
while (true)
35 {
if (!runningflag)
37 {
This.wait ();
39}
Or else
41 {
SYSTEM.OUT.PRINTLN ("Processing" + getargument () + "... done.");
Sleep (5000);
System.out.println ("Thread is sleeping ...");
Setrunning (FALSE);
46}
47}
+} catch (Interruptedexception e) {
System.out.println ("Interrupt");
50}
Wuyi}//end of Run ()
}//end of Class Simplethread
If you're not quite sure about Java's threading programming, so I'll explain briefly here that Java has a class called thread, and if you want to create a thread, you have to inherit from the thread class and implement the Thread class's run () interface to activate a thread , you must call its start () method, and the start () method will automatically invoke the run () interface, so the user must write their application processing logic in the run () interface. So how do we control the thread's sleep and wake? In fact, the Java language has built-in wait () and notify () methods for all objects. When a thread calls the Wait () method, the thread goes to sleep, as if it were parked on the current code, and the following code is not executed, when the Notify () method is invoked, The following code continues from the line of code that invokes the Wait () method, which is somewhat like the concept of breakpoint debugging in the compiler. Take this procedure for example, line 38th calls the Wait () method, and the thread stops at 38 lines like it froze, and if we make a notify () call on line 13th, the thread wakes up from line 38th and continues to execute the following code from the 39th line.
Through the above, we are now not difficult to understand the Simplethread class, the 第9-14 line by setting a flag Runningflag activate the current thread, 第25-29 row is the Simplethread class constructor, which tells the client to start the process of what date. 第31-50 line is my implementation of the run () interface, it is actually an infinite loop, in the loop first to determine the flag runningflag, if there is no runningflag false, that thread to deal with sleep state, Otherwise the 第42-45 guild does the real processing: first print the string the user typed, then sleep for 5 seconds, why sleep for 5 seconds? If you do not add this code, because the computer processing speed far more than your keyboard input speed, so you see is always the 1th thread to handle your request, so that does not achieve the demo effect. The last line 45th calls the Setrunning () method and puts the thread in the sleep state, waiting for the new request to arrive.
The last thing to note is that if you call the Wait () and notify () function in a method, you have to put this method in sync, that is, synchronized, or you will make an error at compile time, and get an inexplicable message: "Current thread Not owner "(the current thread is not the owner).
So far, we have fully implemented a thread pool, of course, this thread pool simply prints the client-input string to the screen without any processing, and for a real enterprise application, this example is far from enough, such as error handling, dynamic tuning of threads, performance optimization, critical area processing, The definition of client message is worth considering, but the purpose of this article is only to let you understand the concept of the thread pool and its simple implementation, if you want to be a master in this field, this article is not enough, you should refer to some more information to understand it in depth.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.