Python multi-Thread programming (3): important functions and methods of the threading. Thread class,
This article mainly introduces some main methods of the main class Thread in the threading module. The example code is as follows:
Copy codeThe Code is as follows:
'''
Created on 2012-9-7
@ Author: walfred
@ Module: thread. ThreadTest3
@ Description:
'''
Import threading
Class MyThread (threading. Thread ):
Def _ init _ (self ):
Threading. Thread. _ init _ (self)
Def run (self ):
Print "I am % s" % (self. name)
If _ name _ = "_ main __":
For I in range (0, 5 ):
My_thread = MyThread ()
My_thread.start ()
Name-related
You can specify the name for each thread, which is in the Thread-No format by default, as shown in the preceding sample code:
Copy codeThe Code is as follows:
I am Thread-1
I am Thread-2
I am Thread-3
I am Thread-4
I am Thread-5
Of course, you can specify the name of each thread. Using the setName method, the Code is as follows:
Copy codeThe Code is as follows:
Def _ init _ (self ):
Threading. Thread. _ init _ (self)
Self. setName ("new" + self. name)
Join Method
The following is a prototype of the join method. This method is used to block the current context until the thread stops running:
Copy codeThe Code is as follows:
Def join (self, timeout = None ):
Timeout can be set to timeout
Timeout can be set to time-out to eat away
SetDaemon Method
When we are running the program, we will execute a main thread. If the main thread creates another sub-thread, the main thread and sub-thread will be divided into two routes. When the main thread completes and wants to exit, checks whether the Sub-thread is complete. If the sub-thread is not completed, the main thread will wait for the sub-thread to complete and then exit. But sometimes we need to exit with the main thread as long as the main thread is completed and the thread is not completed or not. In this case, we can use the setDaemon method, set the parameter to True.
Of course, the above lists the methods we often use in programming. For more methods, see Higher-level threading interface.