#exercise: Create a thread fromThreadingImportThreadImport TimedefRun (a = None, B =None):PrintA, b time.sleep (1) T= Thread (target = run, name="Wangjing", args = ("This is a","Thread"))#the thread is a new state at this timePrintT.getname ()#get Thread object namePrintT.isalive ()#determines whether the thread is still alive, after start, calls IsAlive () before execution completes to return trueT.start ()#Start Thread#print t.isalive ()T.join ()#main thread waits for child thread t to execute endPrint "done!"#exercise: Creating a thread with inherited methods fromThreadingImportThreadImport TimeclassMyThread (Thread):def __init__(Self, a):#calling the parent class's constructor methodSuper (MyThread, self).__init__() SELF.A=adefRun (self): Time.sleep (SELF.A)Print "Sleep:", SELF.A t1= MyThread (2) T2= MyThread (4)#multi-threaded execution is not sequential, this example mainly adds a longer wait time before it appears to have an execution orderT1.start () T2.start () T1.join () T2.join ( )Print "done!"#Exercise: ThreadsImportThreadingImport TimeclassTimer (threading. Thread):#The timer class is derived from the class threading. Thread def __init__(self, num, interval): Threading. Thread.__init__(self) self.thread_num=Num Self.interval=interval Self.thread_stop=FalsedefRun (self):#Overwrite Run () method, put what want the thread does here while notSelf.thread_stop:Print 'Thread Object (%d), time:%s\n'%(Self.thread_num, Time.ctime ()) Time.sleep (Self.interval)defStop (self): Self.thread_stop=TruedefTest (): Thread1= Timer (1, 1) Thread2= Timer (2, 2) Thread1.start ()#execute the Run method inside the classThread2.start () time.sleep (10)#here is the main thread waiting for 10 secondsthread1.stop () thread2.stop ( )#Stop Thread #这里的停止是主线程调用的 if __name__=='__main__': Test ()#exercise: Start a thread in a thread againImportThreadingImport Timedefcontext (Tjoin):Print 'In Threadcontext.'Tjoin.start ()#will block Tcontext until Threadjoin terminatesTjoin.join ()#Tjoin to continue execution after termination Print 'Out Threadcontext.'defjoin1 ():Print 'In Threadjoin.'Time.sleep (1) Print 'Out Threadjoin.'if __name__=="__main__": Tjoin= Threading. Thread (target =join1)#to pass a thread object as a parameter into another threadTcontext = Threading. Thread (target = context, args =(Tjoin,)) Tcontext.start ()#Exercise: Set a child thread as a daemon threadImportThreadingImport TimeclassMyThread (Threading. Thread):def __init__(self, id): threading. Thread.__init__(self)defRun (self): Time.sleep (5) Print " This is"+Self.getname ()if __name__=="__main__": T1= MyThread (999) #T1.setdaemon (True)#sets the child thread as the daemon thread, and after the daemon thread is set, the main thread exits the child thread and then exits, preventing the child thread from suspendingT1.start ()Print "I am The father thread."
"Python" multithreading-1