The thread and threading modules are provided in Python to support multithreading, where the threading module is encapsulated in the thread module and in most cases uses threading for multithreaded programming. I. Using Threading.thread to run functions in a thread
#Coding=utf-8ImportThreading fromTimeImportCTime, SleepdefMusic (func): forIinchRange (2): Print 'Section'I'listen to music!!!! Times' Print 'I was listening to%s.%s'%(Func,ctime ()) Sleep (1)defMove (func): forIinchRange (2): Print 'Section'I'time to see the film!!! ' Print 'I was at the %s!!%s'%(Func,ctime ())defrun (x, y): s=x+yPrint '--------', S,'---------'#running functions in threadsif __name__=='__main__': Threads=[] T1=threading. Thread (target=music,args= (U'Love Business',)) Threads.append (t1) T2=threading. Thread (target=move,args= (U' Avatar',)) Threads.append (T2) T3=threading. Thread (target=run,args= (10,12)) threads.append (T3) forTinchThreads:t.setdaemon (True) T.start () forTinchThreads:t.join ()Print 'All over %s'%ctime ()
Two. Inherit Threading.thread overloaded Run method
#Coding=utf-8ImportThreading fromTimeImportSleepImport Time#inherit threading. Thread class, overriding the Run methodclassMytheard (Threading. Thread):def __init__(self,num): Threading. Thread.__init__(self) self.num=NumdefRun (self):Print 'I am', Self.num Sleep (5) classMythread (Threading. Thread):def __init__(self,ssid,tname): Threading. Thread.__init__(self,name=tname) Self.ssid=SSIDdefRun (self): x=0Printx Time.sleep (10) PrintSelf.ssiddefexample1 (): T1=mytheard (1) T2=mytheard (2) T3=mytheard (3) T1.start () T2.start () T3.start ( )defexample2 (): t=mythread (2,'T1') T.setdaemon (True)#set the thread as the daemon threadT.start ()Printt.getname () t.setname ('T2') PrintT.getname ()#Get thread name PrintT.isalive ()#determine if the thread is still alive PrintT.isdaemon ()#determines whether the thread is a daemon threadT.join ()#blocks the main thread until the threads T execution ends Print 'Work END!!!!' if __name__=='__main__': example2 ()
Python: Multithreading