100 lines of Java code to build a thread pool

Source: Internet
Author: User

In modern operating systems, there is a very important concept-threads. Almost all currently popular Operating Systems Support threads. threads come from the concept of processes in the operating system, A process has its own virtual address space, body segment, data segment, and stack, and each occupies different system resources (such as files and environment variables ).

Two threads are generated, and the two threads share the global variables and code segments of the process, but each thread has its own stack, so they have their own local variables, in Unix systems, threads are further divided into user-level threads (managed by the process itself) and system-level threads (managed by the scheduling program of the operating system ).

Now that there is a process, why do we need to propose the thread concept? Compared with creating a new process, creating a thread will consume much less system resources. For some small applications, this may not be felt, however, for applications with a very large number of concurrent processes, the use of threads will achieve better performance than the use of processes, thus reducing the burden on the operating system. In addition, the thread shares the global variables of the processes that create it. Therefore, the communication programming between threads will be simpler, and the traditional IPC programming for inter-process communication can be completely abandoned, the shared global variables are used for inter-thread communication.

With the above concept, let's start with the question. Let's take a look at what the thread pool is like? In fact, the thread pool principle is very simple. It is similar to the buffer concept in the operating system. The process is as follows: Start a number of threads and make these threads sleep, when the client has a new request, it will wake up a sleep thread in the thread pool and let it process the request from the client. After processing the request, the thread is sleeping again. Maybe you may ask: why is it so troublesome? If a client has a new request, I will not finish creating a new thread? This may be a good method, because it makes it easier for you to write code, but you ignore an important problem-performance! Taking my unit as an example, my unit is a bank network center in a provincial big data set. The number of client request concurrencies per second exceeds 100 during peak periods, if you create a new thread for each client request, the CPU time and memory consumed will be astonishing. If you use a thread pool with 200 threads, this will save a lot of system resources, so that more CPU time and memory are used to deal with actual commercial applications, rather than frequent thread creation and destruction.

Now that everything is clear, let's start to implement a real thread pool. Thread Programming can be implemented in multiple languages, such as C, C ++, and Java, however, different operating systems provide different thread APIs. To help you better understand the principles of the thread pool and avoid getting stuck in cumbersome API calls, I used the Java language to implement it, because Java is a cross-platform language, you do not have to worry about using different operating systems and cannot compile and run the program. If you have installed JDK or later, you can compile and run the program correctly. In addition, the Java language itself has a built-in thread object, and the Java language is completely like an object, so you can have a clearer understanding of the thread pool principle, if you take a look at the title of this article, you will find that the entire sample program has only about 100 lines of code.

This example consists of three classes. The first is the testthreadpool class, which is a test program used to simulate client requests. When you run it, the system will first display the initialization information of the thread pool, and then prompt you to input a string from the keyboard, and press the Enter key, then you will find the information displayed on the screen, it tells you that a thread is processing your request. If you enter a line of string quickly, you will find that there are threads in the thread pool constantly waking up to process your request, in this example, I created a thread pool with 10 threads. If there are no available threads in the thread pool, the system will prompt you with a warning message, but if you wait for a moment, on the screen, you will find that a thread enters the sleep state, and then you can send new requests.

The second class is the threadpoolmanager class. As the name suggests, it is a class used to manage the thread pool. Its main responsibility is to initialize the thread pool, assign different threads to the client for processing. If the thread pool is full, it will send you a warning.

The last class is the simplethread class, which is a subclass of the thread class, which truly processes client requests. simplethread is sleep during initialization of the sample program, however, if it receives the scheduling information sent by the threadpoolmanager class, it will wake itself up and process the request.

First, let's take a 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 ));
10 string S;
11 threadpoolmanager manager = new threadpoolmanager (10 );
12 while (S = Br. Readline ())! = NULL)
13 {
14 manager. Process (s );
15}
16} catch (ioexception e ){}
17}
18}

Because the input class is used in this test program, the basic I/O Processing Package of Java is imported in row 1st. In row 11th, a class named Manager is created, it passes a 10 parameter to the threadpoolmanager class constructor and tells threadpoolmanager class: I want a pool with 10 threads. Create one for me! Rows 12th to 15 are infinite loops. They are used to wait for the user to type and save the string to the S variable, call the process method of the threadpoolmanager class to process the request.

Next we will further track 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;
9 Public void setmaxthread (INT threadcount)
10 {
11 maxthread = threadcount;
12}
13
14 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}
26
27 public void process (string argument)
28 {
29 int I;
30 For (I = 0; I <vector. Size (); I ++)
31 {
32 simplethread currentthread = (simplethread) vector. elementat (I );
33 If (! Currentthread. isrunning ())
34 {
35 system. Out. println ("Thread" + (I + 1) + "is processing:" +
Argument );
36 currentthread. setargument (argument );
37 currentthread. setrunning (true );
38 return;
39}
40}
41 if (I = vector. Size ())
42 {
43 system. Out. println ("pool is full, try in another time .");
44}
45}
46} // end of class threadpoolmanager

Let's first take a look at the constructor of this class, and then look at its process () method. Line 16-24 is its constructor. First, it assigns a value to the member variable maxthread of the threadpoolmanager class. maxthread indicates the maximum number of threads used to control the thread pool. Line 3 initializes an array vector, which is used to store all simplethread classes. This fully reflects the superiority and Artistry of the Java language: If you use C language, at least 100 lines of code must be written to complete the vector function. In addition, the C language array can only accommodate the basic data types of unified types and cannot accommodate objects. Well, let's talk less about it. The loop in line 19-24 completes this function: first create a new simplethread class, then put it into the vector, and finally use thread. start () to start this thread. Why should we use the START () method to start the thread? This is what is specified in the Java language. If you do not need it, these threads will never be activated, causing the program in this example to be unable to run.

 

Next let's take a look at the process () method. The loop in line 30-40 selects the simplethread thread from the Vector Array in sequence, and check whether it is in the active State (the so-called activation state refers to whether the thread is processing client requests). If it is in the active state, continue to look for the next item of the Vector Array, if all threads in the Vector Array are in the active state, it prints a message prompting the user to try again later. On the contrary, if a sleep thread is found, line 35-38 will process the request. It first tells the client which thread is used to process the request, and then sends the client request, that is, the string argument is forwarded to the setargument () method of the simplethread class for processing, and the setrunning () method of the simplethread class is called to wake up the current thread and process client requests.

Maybe you still don't understand how the setrunning () method wakes up the thread. Now we will enter the last class: simplethread class. Its source code is as follows:

// 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 {
11 runningflag = flag;
12 if (FLAG)
13 This. Policy ();
14}
15
16 Public String getargument ()
17 {
18 return this. argument;
19}
20 public void setargument (string)
21 {
22 argument = string;
23}
24
25 public simplethread (INT threadnumber)
26 {
27 runningflag = false;
28 system. Out. println ("Thread" + threadnumber + "started .");
29}
30
31 public synchronized void run ()
32 {
33 try {
34 while (true)
35 {
36 IF (! Runningflag)
37 {
38 this. Wait ();
39}
40 else
41 {
42 system. Out. println ("processing" + getargument () + "... done .");
43 sleep (5000 );
44 system. Out. println ("thread is sleeping ...");
45 setrunning (false );
46}
47}
48} catch (interruptedexception e ){
49 system. Out. println ("interrupt ");
50}
51} // end of run ()
52} // end of class simplethread

If you do not quite understand Java Thread Programming, I will briefly explain here that Java has a class named thread. If you want to create a thread, you must inherit from the Thread class and implement the run () interface of the thread class. to activate a thread, you must call its start () method, start () the method automatically calls the run () interface. Therefore, you must write your own application processing logic in the run () interface. So how can we control the sleep and wakeup of threads? In fact, it is very simple. Java has built-in wait () and notify () methods for all objects. When a thread calls the wait () method, the thread enters the sleep state, it is like stopping the current code and will not continue to execute the following code. When the notify () method is called, wait () the line of code of the method continues to execute the following code. This process is a bit like the concept of breakpoint debugging in the compiler. Taking this program as an example, if the wait () method is called in line 1, the thread stops on line 38 as it is solidified. If we perform a notify () operation in line 3 () if it is called, the thread will wake up from the second line and continue to execute the following code from the second line.

Based on the above description, it is not difficult to understand the simplethread class now. Line 9-14 activates the current thread by setting a flag runningflag. Line 25-29 is the constructor of the simplethread class, it is used to tell the client to start the process number. Line 31-50 is the run () interface implemented by me. It is actually an infinite loop. in the loop, first judge the flag runningflag. If no runningflag is false, the thread will process the sleep state. Otherwise, the thread will perform the actual processing on the 42-45 line: print the user-typed string and then sleep for 5 seconds. Why do we need to sleep for 5 seconds? If you do not add this code, because the computer processing speed is much faster than your keyboard input speed, you will always see Thread 1st to process your request, in this case, the demo effect cannot be reached. The last 45th lines call the setrunning () method and place the thread in sleep state, waiting for the arrival of new requests.

Note that if you call the wait () and notify () functions in a method, you must set this method to synchronous, that is, synchronized, otherwise, an error is reported during compilation and an inexplicable message is displayed: "current thread not owner" (the current thread is not the owner ).

So far, we have completely implemented a thread pool. Of course, this thread pool simply prints the string entered by the client to the screen without any processing, for a real enterprise-level application, this example is far from enough, for example, error processing, dynamic adjustment of threads, performance optimization, processing of critical sections, and definition of client packets are all worth considering, however, 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 become a master in this field, this article is far from enough, for more information, see.

Reprinted original address: http://blog.csdn.net/luedipiaofeng/article/details/1651442

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.