python多线程
来源:互联网 发布:矢仓枫子 知乎 编辑:程序博客网 时间:2024/06/10 18:02
本文主要采用threading库
import threading
线程创建:
- 方法一:传入参数实例化线程。
- 函数:threading.Thread(target, args)
- target:函数名
- args:传入target函数的参数,用元组保存
- 函数:threading.Thread(target, args)
# encoding:utf-8# coding:utf-8import threadingdef print_time(thread_name, delay): print '线程{thread_name}启动'.format(thread_name=thread_name) count = 0 while count < 5: print 'count:%d' % count # 将线程阻塞delay秒 # time.sleep(delay) count += 1if __name__ == '__main__': thread1 = threading.Thread(target=print_time, args=('thread1', 1)) thread2 = threading.Thread(target=print_time, args=('thread2', 2)) thread1.start() thread2.start()
- 方法二:继承thread.Thread类,重写_init_()与_run_()方法
# coding:utf-8import threadingclass ThreadTest(threading.Thread): def __init__(self, name): threading.Thread.__init__(self) self.name = name def run(self): print '线程{name}启动'.format(name=self.name) count = 0 while count < 5: print 'count:%d' % count count += 1if __name__ == '__main__': thread1 = ThreadTest('thread1') thread2 = ThreadTest('thread2') thread1.start() thread2.start()
看到这里的时候,刚接触多线程的你(接触过的可以省略这段)会发现运行的结果和我的不一致,不用紧张,多线程执行的过程并不是线性的,结果是不可预测的。强推以下文章,理解线程的执行过程:python 线程详解–AstralWind
线程通信:
阅读全文
0 0
- Python多线程
- Python多线程
- Python多线程
- python多线程
- python 多线程
- python多线程
- python多线程
- python 多线程
- python多线程
- Python多线程
- Python 多线程
- python多线程
- python 多线程
- {python多线程}
- Python 多线程
- Python多线程
- python 多线程
- Python 多线程
- 树链剖分
- 【转】前端框架基础:Babel & package.json & npm & nodemon
- 一位数组>>>>>>>>>>约瑟夫环
- 树状数组实现 区间修改+区间查询
- HDU-2017 多校训练赛4-1004-Dirt Ratio
- python多线程
- B
- 中大型网站架构的演变之路
- 自定义view继承view
- Oracle 分组函数
- G
- cf632e dp
- 磁盘管理4--磁盘阵列RAID
- mac 使用技巧(持续更新)