Python多线程 - 使用threading模块实现多线程的 3 种方式
2018-01-05 14:47
1041 查看
方式一: 创建Thread的实例,并给它传递一个函数对象
# -*- coding:utf-8 -*- import threading import time loops=[4,2] def loop(nloop,nsec): print("starting loop"+str(nloop)+" at "+time.ctime()) time.sleep(nsec) print("loop"+str(nloop)+" done at "+time.ctime()) def main(): print("starting main at "+time.ctime()) threads=[] nloops=range(len(loops)) # 创建线程对象 for i in nloops: t=threading.Thread(target=loop,args=(i,loops[i])) threads.append(t) # 开启线程 for i in nloops: threads[i].start() # 阻塞线程(主线程会等待当前线程执行完毕后,才会继续运行) for i in nloops: threads[i].join() print("loop main done at "+time.ctime()) if __name__=="__main__": main()
方式二: 创建Thread的实例,并给它传递一个可调用的类对象
# -*- coding:utf-8 -*- # 方式二:创建Thread的实例,传给它一个可调用的类实例 import threading import time loops=[4,2] def loop(nloop,nsec): print("starting loop"+str(nloop)+" at "+time.ctime()) time.sleep(nsec) print("loop"+str(nloop)+" done at "+time.ctime()) class MyClass(object): def __init__(self, func,args,name=""): self.func=func self.args=args self.name = name def __call__(self): self.func(*self.args) def main(): print("starting main at "+time.ctime()) threads=[] nloops=range(len(loops)) # 创建线程对象 for i in nloops: t=threading.Thread(target=MyClass(loop,(i,loops[i]),name=loop.__name__)) threads.append(t) # 开启线程 for i in nloops: threads[i].start() # 阻塞线程 for i in nloops: threads[i].join() print("loop main done at "+time.ctime()) if __name__=="__main__": main()
方式三:派生Thread的子类,并创建子类的实例
# -*- coding:utf-8 -*- import threading import time loops=[4,2] def loop(nloop,nsec): print("starting loop"+str(nloop)+" at "+time.ctime()) time.sleep(nsec) print("loop"+str(nloop)+" done at "+time.ctime()) class MyThread(threading.Thread): def __init__(self,func,args,name=""): super(MyThread,self).__init__() self.func=func self.args=args self.name=name def run(self): self.func(*self.args) def main(): print("starting main at "+time.ctime()) threads=[] nloops=range(len(loops)) # 创建线程实例 for i in nloops: t=MyThread(loop,(i,loops[i]),name=loop.__name__) threads.append(t) # 开启线程 for i in nloops: threads[i].start() # 阻塞线程 for i in nloops: threads[i].join() print("loop main done at "+time.ctime()) if __name__=="__main__": main()
相关文章推荐
- Python:使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程编程一[综述]
- python学习笔记之使用threading模块实现多线程(转)
- [Python module]使用threading模块实现多线程编程一[综述]
- Python:使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程编程一[综述]
- python3 使用threading模块进行多线程编码实现
- Python:使用threading模块实现多线程
- python学习笔记之使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程
- Python:使用threading模块实现多线程编程二[两种方式起线程]
- python学习笔记之使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程
- Python:使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程编程一[综述]
- Python:使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程编程二[两种方式起线程]