What is multi-thread programming?
Multithreading programming is an important feature of Java. Multi-threaded programming refers to dividing program tasks into several parallel subtasks. Especially in network programming, you will find that many functions can be executed concurrently. For example, if the network transmission speed is slow and user input speed is slow, you can use two independent threads to complete these two functions without affecting normal display or other functions.
Multithreading is compared with a single thread. In common Windows, a single thread program structure is used. its working principle is that the main program has a message loop, reading messages from the Message Queue constantly determines what to do next. It is generally for a function. The main program can receive other messages for execution only after the function is executed. For example, a sub-function is used to read network data or a file. Only after reading the data or file can it receive the Next message. You can't do anything during the execution of this subfunction. However, Network Data Reading and waiting for user input often takes a lot of time to wait. multithreading can solve this problem after dividing a task into multiple concurrent tasks.
Java Thread class
To learn multithreading programming in Java, you must know how to implement classes that support multithreading. There are two methods to implement multi-threaded classes in Java:
1. Extend the java. lang. Thread class and use it to overwrite the run method of the Thread class.
2. Generate a class that implements the java. lang. Runnable interface and associate other instances with the java. lang. Thread instance.
The Thread class is the main class responsible for providing Thread support to other classes. To use a class with the Thread function, in Java, you can simply derive a subclass from the Thread class to extend the Thread class, such as printThread. java.
The following describes how to use these two methods to write your own multi-threaded applications through examples.
Create a subclass of the java. lang. Thread class
The most important method of the Thread class is the run method. The run method is the method executed by the new Thread. Therefore, when a subclass of java. lang. Thread is generated, the corresponding run method must exist.
// PrintThread. java
Public class PrintThread extends Thread // inherits the Tread class
Private int count = 0 // defines a count variable to count the number of prints and share the variable.
Public static void mainString args // start with the main method
PrintThread p = new PrintThread // create a thread instance
P. start // execution thread
For {;}// the main thread main method executes a loop, and for executes an endless loop
Count ++
System. out. printcount + ": Main/n" // print the value of the count + "main" variable in the Main thread and wrap the line.
Public void run // The run () method required by the Thread class
For {;;}
Count ++
System. out. printcount + ": Thread/n ″ |
The above program inherits java. lang. Tread and overwrites run. When starting a program with a Java virtual machine, the program will become a thread and call the main method of the main class of the program. The main method in this program generates a new Thread, and the connection prints "Thread ". After the thread is started, the Main thread continues to print "Main ".
Compile and execute this program, and then immediately press the "Ctrl + C" key to interrupt the program. You will see that the two threads mentioned above are constantly printing out: XXX: main ..... XXX: Thread .... XXX represents a number, that is, the value of count above. On the author's machine, the printing times of these two threads are different at different times. Print 20 main threads (that is, execute 20 main threads first) and then print 50 threads, then print the main ......
Tip: To facilitate viewing the execution result of the program, you can import the execution result into a text file and open the file to view the execution status of each thread. For example:
Javac PrintThread. java
Java PrintThread> 1.txt
The first command javac printthread.javais to compile the Java program. The second command is to execute the program and import the result to the 1.txt file. In this way, open this file and you will see the detailed results (note: the execution time of the program cannot be too long, and the 1.txt file will not be generated very large ). Of course, you can directly execute the command: java PrintThread.
Implement the java. lang. Runnable interface
Another way to run a thread is to implement the Runnable interface and generate a thread that runs this class. The Runnable interface is an interface defined in the java. lang Package, which only provides an abstract run declaration.
Next, let's take a look at how to implement the Runnable interface, instead of extending the Thread class.
// PrintRunnableThread. java implements the Runnable interface
Public class PrintRunnableThread implements Runnable
Public static void mainString args
Thread t = new Threadnew PrintRun
NableThread
// T. setPriorityThread. MAX_PRIORI
TY // set the maximum priority
T. start // thread start
For {;} // print the character M continuously, representing the main thread
System. out. println "M ″
Public void run
For {;} // print the character T continuously, representing the thread
System. out. println "T ″ |
Run this program and you will find that the execution result is similar to that of PrintThread. java. You can even add another variable and print similar thread execution results.
Note: Unlike the delimiter, if the annotator before the t. setPriorityThread. MAX_PRIORITY statement is removed, the thread is set to the maximum priority, and the execution result is quite different.
Thread group ThreadGroup
The java. lang. ThreadGroup class indicates a group of threads (which may contain other threadgroups). It is used to implement centralized thread group management based on specific functions. Each thread created by the user belongs to a thread group. This thread group can be specified when the thread is created, or the thread group can be left unspecified to keep the thread in the default thread group. However, once a thread is added to a thread group, the thread remains in the thread group until the thread is terminated. The thread group to which the thread belongs cannot be changed midway through.
The following code demonstrates how to operate and use ThreadGroup.
// ThreadGroupTest. java
Public class ThreadGroupTest implements Runnabl
E
Public void run
Public static void main (String args [])
// Generate a new thread group and put two thread objects in the group.
ThreadGroup threadgroup = new ThreadGroup "thread group ″
Thread t1 = new Threadthreadgroupnew ThreadGrou
PTest "thread 1 ″
Thread t2 = new Threadthreadgroupnew ThreadGrou
PTest "thread 2 ″
// Find the top-level parent thread
ThreadGroup parent = Thread. currentThread. getThrea
DGroup // obtain the thread group of the current thread
Whileparent. getParent = null
Parent = parent. getParent // get the parent thread
// The list method prints out all content threads and subthread groups of the current thread group.
Parent. list |
Tip: In the previous program, the list () method displays the structure and content of the ThreadGroup tree (which may include threads and thread groups, so it constitutes a Thread Tree. Run the above program and you will have a certain understanding of the thread group.
Thread priority
Although we say that threads run concurrently. However, this is often not the case. When there is only one CPU in the system, executing multiple threads in a single CPU in some order is called scheduling. Java adopts a simple and fixed scheduling method, namely, fixed priority scheduling. This algorithm is implemented based on the relative priority of the runable thread. When a thread is generated, it inherits the priority of the original thread. You can modify the priority as needed. If multiple threads are waiting for the running system to run at any time, select the highest-priority runable thread. It can only run when it is stopped, automatically abandoned, or for some reason a thread with a non-running priority. If two threads have the same priority, they are run alternately.
The first Thread in Java has a priority. The priority of a Thread is an integer between Thead. MIN_PRIORITY and Thread. MAX_PRIORITY between 0 and 10. By default, the thread priority is 5, that is, NORM_PRIORITY. We can use expressions such as Thread. setPriorityThread. MIN_PRIORITY to set the priority of a Thread, which will be used in the routine later. You can also get the thread priority through getPriority, or change the thread priority at any time after the thread is created by setPriority.
Tip: When the code in the thread creates a new thread object, the new thread has the same priority as the thread that created it.
Thread Management
A single-threaded program has a main execution body that runs some code. After the program is executed, the program stops running. To get the same response in Java, we must make slight changes. The program can end only when all threads exit. As long as one thread is running, the program cannot exit.
Threads include new () Start, running () Run, wait () wait, and done end execution status. When a thread is created for the first time, it is in the new State. In this state, the thread cannot be run and can only wait. At this time, the thread either calls the start method to start running or sends it to the done state to end. The thread in done has finished execution, which is the last state of the thread. Once a thread is in this state, it cannot appear again. When all threads in the Java Virtual Machine are in the done state, the program is forcibly aborted.
All threads currently being executed are in the running state. Some method is used between programs to divide the execution time of the processor into time slices. Every thread in the running state can run, but each system processor can run only one thread at a given time. Unlike a thread in the running state, you can delete a thread in the waiting state from a set of executable threads for some reason. If the thread execution is interrupted, it will return to the waiting state. At this time, the thread may be suspended, waiting on system resources, or being told to enter Sleep state. A thread in this state can return to the running state, and can also be sent to the done state from stop. The Thread class provides Sleep (), Stop, Yield (), Suspend (), and Resume () methods to manage threads.
Other concepts of thread operations
Through the study of these two programs, you may think that the Java thread operation is very simple, but this is not the case. In practice, many problems may need to be considered comprehensively, for example, set monitoring thread, pause, name and coordinate thread, set thread priority, shared variable, thread synchronization, thread pool, thread group, etc. The operations related to these threads are not described in detail in this chapter. If you are interested, you can refer to the relevant monographs. After all, this part is not completely explained in one or two articles.