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... as shown in the previous section, the threading of python. the Thread class has a run method, which is used to define the function of a Thread and can be overwritten in its 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-8import threadingimport time class MyThread(threading.Thread): def run(self): for i in range(3): time.sleep(1) msg = "I'm "+self.name+' @ '+str(i) print msgdef 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
We can see from the code and execution results that the execution sequence of multi-threaded programs 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.