100 lines of Java code build a thread pool

xiaoxiao2021-03-06  85

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 we look at the source 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} catches (ioException 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 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 If you don't quite understand the Java thread programming, then I will simply explain here, Java has a class named Thread, such as If you want to create a thread, you must inherit from the Thread class, and you must implement the RUN () interface of the Thread class. To activate a thread, you must call its start () method, start () method automatically calls Run () Interface, the user must write its own application processing logic in the run () interface. So how do we control threads' sleep and awakening? In fact, it is very simple, and the Java language has built WAIT () and notify () methods for all objects. When a thread calls the wait () method, the thread enters the sleep state, just like stopping the current code, no It will continue to perform the following code. When the Notify () method is called, the following code will continue to be executed from the line of call to the wait () method, this process is a bit like the concept of breakpoint debug in the compiler. Taking this procedure as an example, the 38th line calls the wait () method, then the thread will stop in 38 like solidification, if we perform a notify () call at line 13, that thread will On line 38, wake up and continue to perform the following code from line 39.

转载请注明原文地址:https://www.9cbs.com/read-106099.html

New Post(0)