As in the previous section, the threading. Thread class of Python has a run method used to define the function functions of a thread. You can override this method in your own Thread class. After creating your own thread instance, you can start the thread through the start method of the thread class and submit it to the python Virtual Machine for scheduling. When the thread gets the chance of execution, the run method execution thread is called. Let's start with the first example:
# Encoding: UTF-8
Import threading
Import time
Class mythread (threading. Thread ):
Def run (Self ):
For I in range (3 ):
Time. Sleep (1)
MSG = "I'm" + self. Name + '@' + STR (I)
Print msg
Def test ():
For I in range (5 ):
T = mythread ()
T. Start ()
If _ name _ = '_ main __':
Test ()
Execution result:
I'm thread-1 @ 0
I'm thread-2 @ 0
I'm thread-5 @ 0
I'm thread-3 @ 0
I'm thread-4 @ 0
I'm thread-3 @ 1
I'm thread-4 @ 1
I'm thread-5 @ 1
I'm thread-1 @ 1
I'm thread-2 @ 1
I'm thread-4 @ 2
I'm thread-5 @ 2
I'm thread-2 @ 2
I'm thread-1 @ 2
I'm thread-3 @ 2
SlaveCodeAnd the execution results, we can see that MultithreadingProgramThe execution sequence of is uncertain. When a sleep statement is executed, the thread is blocked. After sleep is finished, the thread enters the ready state and waits for scheduling. Thread Scheduling selects a thread for execution. The code above can only ensure that each thread runs a complete run function, but the thread startup sequence and the execution sequence of each loop in the run function cannot be determined.
Note the following:
1. Each thread must have a name. Although the name of the thread object is not specified in the preceding example, Python automatically specifies a name for the thread.
2. When the run () method of the thread ends, the thread is finished.
3. The thread scheduling program cannot be controlled, but other methods can be used to affect the thread scheduling mode.
The preceding example demonstrates how to create a thread, actively suspend the thread, and exit the thread. In the next section, we will discuss how to use mutex lock for thread synchronization.