#Coding=utf-8ImportThreading fromTimeImportCtime,sleepdefMusic (func): forIinchRange (2): Print "I was listening to%s.%s"%(Func,ctime ()) Sleep (1)defMove (func): forIinchRange (2): Print "I was at the %s!%s"%(Func,ctime ()) Sleep (5) Threads=[]t1= Threading. Thread (target=music,args= (U'Love Business',)) Threads.append (t1) T2= Threading. Thread (target=move,args= (U' Avatar',)) Threads.append (T2)if __name__=='__main__': forTinchThreads:t.setdaemon (True) T.start ()
For T in Threads:
T.join ()
Print "All over %s"%ctime ()
Threads = []
T1 = Threading. Thread (target=music,args= (U ' Love Trade ',))
Threads.append (T1)
Creates a threads array, creates thread T1, and uses threading. The Thread () method, in which the music method is called by the Target=music,args method to pass a parameter to the music. Load the created thread T1 into the threads array.
The thread T2 is then created in the same way, and the T2 is also loaded into the threads array.
For T in Threads:
T.setdaemon (True)
T.start ()
Finally, the array is traversed by a for loop. (the array is loaded with T1 and T2 two threads)
Setdaemon ()
Setdaemon (True) declares a thread as a daemon thread and must be set before the start () method call, if not set to the daemon, is indefinitely suspended. After the child thread is started, the parent thread continues to execute, and when the parent thread finishes executing the last statement print "All over%s"%ctime (), it exits without waiting for the child thread, and the child threads end together.
Note: However, if we run the program in interactive mode (for example, run with idle), the main thread terminates only when Python exits, so t1,t2 will continue to print and will not have this problem if the. py file is run directly.
Start ()
Starts the thread activity.
Join ()
The principle of join here is to verify that threads in the thread pool end in turn, block until the end of the thread, and then jump to execute the join function of the next thread if it ends.
Python Threading Module