python 多线程编程
来源:互联网 发布:java运维实施岗位职责 编辑:程序博客网 时间:2024/06/05 00:13
使用threading模块的Thread类来创建线程,介绍常用的三种方法:
1.创建一个Thread类的实例,传入一个函数
#coding=utf-8import threading, timeloops=[4,2]def func(index, sec): print "func starts:%d"%(index)+" %s\n"%(time.ctime()) time.sleep(sec) print "func ends:%d"%(index)+" %s\n"%(time.ctime())def main(): threads =[] nloop = range(nlen(loops)) for i in nloop: tt = threading.Thread(target=func, args=(i, loops[i])) print "the name of the threadind:%s\n"%(tt.getName()) threads.append(tt) for i in nloop: threads[i].start() for i in nloop: threads[i].join() #允许主线程等待所有的线程运行完之后在执行后面的逻辑 print "all done:%s\n"%(time.ctime())if __name__ == "__main__": main()2.创建一个Thread类实例,传入以个可调用的类对象
#coding=utf-8import time, threadingloops=[4,2]class MyThread(object): def __init__(self, func, args,name=""): self.args = args self.func = func self.name = name def __call__(self, *args, **kwargs): self.func(*self.args)def loop(nloop, nsec): print "loop starts:%d"%(nloop) + " %s\n"%(time.ctime()) time.sleep(nsec) print "loop ends:%d"%(nloop) + " %s\n"%(time.ctime())def main(): threads =[] for i in range(len(loops)): tt = threading.Thread(target=MyThread(loop, (i,loops[i]),loop.__name__)) #仅修改了这里 print "线程名字:",tt.getName() threads.append(tt) for i in range(len(loops)): threads[i].start() for item in threads: item.join() print "all done:%s\n"%(time.ctime())if __name__ == "__main__": main()3.子类化Thread类,创建一个子类的实例
#coding=utf-8import threading,timeloops=[4,2]class MyThread(threading.Thread): def __init__(self,index, sec): threading.Thread.__init__(self) self.index = index self.sec = sec def run(self): print "loop starts:%d"%(self.index) + " %s\n"%(time.ctime()) time.sleep(self.sec) print "loop ends:%d"%(self.sec) + " %s\n"%(time.ctime())def main(): nloop = range(len(loops)) threads = [] for i in nloop: tt = MyThread(i,loops[i]) print "线程名字:",tt.getName() threads.append(tt) for i in range(len(loops)): threads[i].start() for item in threads: item.join() print "all done:%s\n"%(time.ctime())if __name__ == "__main__": main()
0 0
- Python多线程编程
- Python多线程编程
- Python多线程编程
- python 多线程编程
- python 多线程编程
- zt:python多线程编程
- Python多线程编程
- Python多线程编程
- Python多线程编程
- Python多线程编程
- python 多线程编程
- python 多线程编程
- python sqlite多线程编程
- python 多线程编程
- python多线程编程
- python多线程编程
- python 多线程编程
- python多线程编程
- Android 学习之自定义View
- 受到助教的启发,来写博文记录自己在学习上的成长
- 线性时间排序: 三种非基于比较的内部排序算法
- AngularJS控制器之间的通信
- iOS---collectionView
- python 多线程编程
- ctrl+alt+方向键 与win7的旋转屏幕冲突解决
- ZuoyeOc--父打子
- Android 4.3 BLE 开发samples for SDK单独下载
- IO Brief
- Qt常用快捷键
- cocos2d-x 学习笔记
- Spark中的combineByKey
- 数据结构与算法 -排序