Introductory case
1 Import Threading,time2 " "3#线程的创建有两种方式,1. Call directly,2. Inheritance4 " "5 # def run (n):6# Print ('Test', N)7# #1. Call Directly8# t1 = Threading. Thread (target=run,args= (1,))9# t2 = Threading. Thread (target=run,args= (2,))Ten # T1.start () One # T2.start () A# #2. Inheritance -#classMythread (Threading. Thread): - # def __init__ (self,n): the # Super (mythread,self). __init__ () -# SELF.N =N - # def run (self): -# Print ('Test', SELF.N) +# t1 = Mythread (1) -# t2 = Mythread (2) + # T1.start () A # T2.start () at #统计多个线程耗时, taking into account the concurrent execution of the thread, each thread points to its own, the main course will end automatically after execution, and the time statistic idea of concurrent execution is to use the Jion () method after the threads execution, similar to the Java Wait () - def run (n): -Print'thread-', N)
#为了更加直观的看到多线程执行的效果, we use the Sleep method -Time.sleep (2) -Start_time =time.time () -T_list = [] in forIinchRange -): -t = Threading. Thread (target=run,args= ('{}'. Format (str (i)) ) to T.start () + t_list.append (t) - forJincht_list: the J.join () *End_time =time.time () $Print'Cost Time =', End_time-start_time)
Python Multi-Threading implementation