The relationship between threads
#-*-Coding:utf-8-*-__author__ = "MuT6 sch01ar" import threadingimport timedef MyThread (n): print ("Running Thread", N) print (Threading.current_thread ()) #打印当前线程的类型 Time.sleep (2) for I in range: t = Threading. Thread (target=mythread,args= (i,)) T.start () print ("Running Main threading", Threading.current_thread ()) Print ( Threading.active_count ()) #计算线程数
Run results
The main thread executes at the same time as the child thread, and the script executes the Time.sleep (2) in the Mythread function, running for about 2 seconds.
The number of threads is the sum of the current main thread and the number of child threads
def MyThread (n): print ("Running Thread", N) print (Threading.current_thread ()) Time.sleep (2) for I in Range: t = Threading. Thread (target=mythread,args= (i,)) T.start ()
This code is a child thread that is started by the main thread
Print ("Running Main threading", Threading.current_thread ()) print (Threading.active_count ())
The thread that this code executes for the main thread
multi-threaded wait
#-*-Coding:utf-8-*-__author__ = "MuT6 sch01ar" import threadingimport timeall_thread = []def MyThread (n): print ("Ru Nning ", N," Thread ") Time.sleep (2) for I in range: t = Threading. Thread (target=mythread,args= (i,)) T.start () print ("Finished all Sub-thread")
Run, view results
The script executes both the main thread and the child thread
You can use the wait () if you want to execute the child thread and then perform the main threads first.
#-*-Coding:utf-8-*-__author__ = "MuT6 sch01ar" import threadingimport timeall_thread = []def MyThread (n): print ("Ru Nning ", N," Thread ") Time.sleep (2) for I in range: t = Threading. Thread (target=mythread,args= (i,)) T.start () all_thread.append (t) for T in All_thread: t.join () print (" Finished all Sub-thread ")
Run, view results
The child thread is executed first, then the main thread is stopped for about 2 seconds.
Multi-threaded Python