Python 创建线程
来源:互联网 发布:美国政治正确 知乎 编辑:程序博客网 时间:2024/06/06 00:18
关于 线程 是什么东东 就不介绍了,直接进入正题。
Python 有多个模块可以支持多线程,thread,threading,Queue。此处不提Queue,有兴趣自己了解
thread模块提供了基本的线程和锁得支持,threading 提供了更全面的更高级的线程支持。因此除非特别需要,否则请使用threading而不是thread。
Python创建线程一般来说有三种方式:
1.创建一个Thread对象,传入一个函数
2.创建一个Thread对象,传入一个可调用的类对象
3.创建一个类对象,该对象继承自Thread
至于如何创建线程,请看个人爱好与需求
第一种方式: 创建一个Thread对象,传入一个函数
import threadingfrom time import ctime,sleepdef func(thread): print 'i am thread',thread,'nothing else' sleep(5) print 'thread',thread,'is over'def main(): t1 = threading.Thread(target = func,args = (1,)) sleep(2) t2 = threading.Thread(target = func,args = (1,)) t1.start() t2.start() t1.join() t2.join() if __name__ == '__main__': main()
Thread 的 args 参数要求 必须返回一个迭代器,因此 把 (1,) 改为 1 是不可以的 ,会报错。如下
start() 开始线程
join() 等待线程结束
第二种方式:创建一个Thread对象,传入一个可调用的类对象
import threadingfrom time import ctime,sleepclass Mythread (object) : def __init__(self,func,args): self.func = func self.args = args def __call__(self): self.func(self.args)def func(thread): print 'i am thread',thread,'nothing else' sleep(5) print 'thread',thread,'is over'def main(): t1 = threading.Thread(target=Mythread(func,1)) t2 = threading.Thread(target=Mythread(func,2)) t1.start() sleep(2) t2.start() t1.join() t2.join() if __name__ == '__main__': main()
第三种方式:创建一个类对象,该对象继承自Thread
import threadingfrom time import ctime,sleepclass MyThread(threading.Thread): def __init__(self,func,args): threading.Thread.__init__(self) self.func = func self.args = args def run(self): self.func(self.args)def func(thread): print 'i am thread',thread,'nothing else' sleep(5) print 'thread',thread,'is over'def main(): t1 = MyThread(func,1) t2 = MyThread(func,2) t1.start() sleep(2) t2.start() t1.join() t2.join()if __name__ == '__main__': main()
更多线程方面细节知识,请查阅Python 核心编程。
本人初学者。如何任何不当之处,欢迎指正,谢谢!
0 0
- python之创建线程
- python创建线程
- python 线程池创建
- 【Python】批量创建线程
- Python 创建线程
- Python线程的创建
- python创建线程
- 用python创建线程池
- python 线程池的创建
- Python练习代码 -- 线程创建, 同步
- Python多线程之线程创建和终止
- Python线程的两种创建方法
- python多线程编程—创建线程
- Python 使用threading 模块创建线程
- python 创建多个线程并启动
- python基础-线程创建、线程池、进\线程异步回调(add_done_callback)、进\线程数据共享、ftp线程池
- 【Python】线程的创建、执行、互斥、同步、销毁
- Python 3基础教程38-threading和创建一个线程
- 超级素数幂
- 扩展ThreadPoolExector
- 如何解决Android eclipse 使用RecyclerView和CardView控件时报错问题
- Android-6.0之PMS安装APK下篇
- gcc和gdb的使用
- Python 创建线程
- 浅谈React实现搜索匹配
- Android-6.0之PMS卸载APK
- 影响网页内容的七种设计误区
- FUZZ初学笔记(二)
- 内核态与用户态通信方式——Nelink
- 学习淘淘商城第三十三课(使用Spring来管理Redis单机版和集群版)
- 等价二叉树
- ajax篇 ajax格式