Python零基础入门--基础(十五)- 线程Threading模块调用疑问

it2022-05-05  179

 一、singleThread()方法为什么是依次执行

#/usr/bin/python #-*- coding: UTF-8 -*- import threading import time,datetime #继承类对象 class MyThread(threading.Thread): def __init__(self,func,args): super(MyThread,self).__init__() # threading.Thread.__init__(self) self.func = func self.args = args def run(self): self.func(**self.args) class sayhiclass: def __init__(self,num): self.num = num def sayhi(self,**kwargs): print ('thread %s Start.'%threading.current_thread().name) #子线程 job_name = kwargs.pop("taskname", None) print ('thread %s End.'%threading.current_thread().name) #子线程 time.sleep(5) def sayhi(num): #定义每个线程要运行的函数 print ('thread %s Start.'%threading.current_thread().name) #子线程 time.sleep(5) print ('thread %s End.'%threading.current_thread().name) #子线程 def singleThread(): print("start %s :%s" %(threading.current_thread().name,datetime.datetime.now())) tlist = [] for i in [1,2,3]: dict = {"taskname" : i} t = threading.Thread(target=sayhiclass.sayhi(i,taskname = i )) #依次执行 tlist.append(t) t.start() for t in tlist: t.join() print("End %s :%s" %(threading.current_thread().name,datetime.datetime.now())) def multiThread(): print("start %s :%s" %(threading.current_thread().name,datetime.datetime.now())) tlist = [] for i in [1,2,3]: t = threading.Thread(target=sayhi,args=(i,)) # 多线程执行 tlist.append(t) t.start() for t in tlist: t.join() print("End %s :%s" %(threading.current_thread().name,datetime.datetime.now())) def multiThreadClass(): tlist = [] for i in [1]: dict = {"taskname" : i} t = MyThread(sayhiclass.sayhi(i),dict ) # 多线程执行 tlist.append(t) for t in tlist: t.start() for t in tlist: t.join() if __name__ == '__main__': singleThread() multiThread() # multiThreadClass()

执行结果:

start MainThread :2019-07-18 12:06:49.499546 thread MainThread Start. thread MainThread End. thread MainThread Start. thread MainThread End. thread MainThread Start. thread MainThread End. End MainThread :2019-07-18 12:07:04.515879 start MainThread :2019-07-18 12:07:04.515949 thread Thread-4 Start. thread Thread-5 Start. thread Thread-6 Start. thread Thread-4 End. thread Thread-5 End. thread Thread-6 End. End MainThread :2019-07-18 12:07:09.521839

 


最新回复(0)