[python] 多线程编程
来源:互联网 发布:网络用语qq爱是什么 编辑:程序博客网 时间:2024/05/02 04:33
方法一:使用thread模块
首先看一下代码:
import threadimport timedef print_time(threadName,delay):count=0while count<5:time.sleep(delay)count += 1print "%s: %s" % (threadName,time.ctime(time.time()))try:thread.start_new_thread(print_time,("Thread-1",2))thread.start_new_thread(print_time,("Thread-2",4))except:print "Error:unable to start thread"while 1:pass运行的结果为:
代码中的
while 1:pass是很有必要的,因为如果删除了这段代码,程序会报出如下的错误
错误的产生原因是:
启动线程之后,需确保主线程等待所有子线程返回结果后再退出,如果主线程比子线程早结束,无论其子线程是否是后台线程,都将会中断,抛出这个异常。
方法二:使用Threading模块创建线程
使用Threading模块创建线程,直接从threading.Thread继承,然后重写_init_方法和run方法
# -*- coding: UTF-8 -*-import threadingimport timeexitFlag = 0class myThread (threading.Thread):#继承父类threading.Threaddef __init__(self, threadID, name, counter):threading.Thread.__init__(self)self.threadID = threadIDself.name = nameself.counter = counterdef run(self):#把要执行的代码写到run函数里,线程在创建后会直接运行run函数print "Starting " + self.nameprint_time(self.name,self.counter,5)print "Exiting" + self.namedef print_time(threadName,delay,counter):while counter:if exitFlag:thread.exit()time.sleep(delay)print "%s,%s" % (threadName,time.ctime(time.time()))counter -=1#创建新线程thread1 = myThread(1,"Thread-1",1)thread2 = myThread(2,"Thread-2",2)#开启线程thread1.start()thread2.start()print "Exiting Main Thread"
程序运行的结果
1:
2:
备注:两次运行的结果不同。
网上有两篇比较好的文章:
http://www.runoob.com/python/python-multithreading.html
http://www.aichengxu.com/view/34207
0 0
- Python多线程编程
- Python多线程编程
- Python多线程编程
- python 多线程编程
- python 多线程编程
- zt:python多线程编程
- Python多线程编程
- Python多线程编程
- Python多线程编程
- Python多线程编程
- python 多线程编程
- python 多线程编程
- python sqlite多线程编程
- python 多线程编程
- python多线程编程
- python多线程编程
- python 多线程编程
- python多线程编程
- 什么是常识?一个人独立生活所具备的能力
- 让我们来FirePHP
- 最近工作中,比较常用的linux命令,稍作整理
- 遍历Map的四种方法
- 用segmentedControl控制显示n个页面之一(思想、思路、无代码)--iOS开发
- [python] 多线程编程
- 点击事件
- 最新版本的phonegap环境搭建(win7)以及项目名称MainActivity问题
- Handler引起的内存泄露
- Ubuntu登录界面输入正确密码依然无法登陆
- 如何在OS X Yosemite 配置php web站点及虚拟主机?
- 英语晨读活动有感
- Hibernate Criteria examples by mkyong
- zzuli OJ 1111: 多个整数的逆序输出(函数专题)