python多线程编程(8):线程的合并和后台线程
2015-08-05 17:38
567 查看
本文转载自:http://www.cnblogs.com/holbrook/archive/2012/03/21/2410120.html
执行结果:
Thread-1 will wait 3 seconds
Thread-2 will wait 4 seconds
Thread-3 will wait 1 seconds
Thread-4 will wait 5 seconds
Thread-5 will wait 3 seconds
main thread is waitting for exit...
Thread-3 finished!
Thread-1 finished!
Thread-5 finished!
main thread finished!
Thread-2 finished!
Thread-4 finished!
对于sleep时间过长的线程(这里是2和4),将不被等待。
执行结果:
main thread is waitting for exit...
Thread-1 will wait 3 seconds
Thread-2 will wait 3 seconds
Thread-3 will wait 4 seconds
Thread-4 will wait 7 seconds
Thread-5 will wait 7 seconds
main thread finished!
可以看出,主线程没有等待子线程的执行,而直接退出。
线程的合并
python的Thread类中还提供了join()方法,使得一个线程可以等待另一个线程执行结束后再继续运行。这个方法还可以设定一个timeout参数,避免无休止的等待。因为两个线程顺序完成,看起来象一个线程,所以称为线程的合并。一个例子:import threading import random import time class MyThread(threading.Thread): def run(self): wait_time=random.randrange(1,10) print "%s will wait %d seconds" % (self.name, wait_time) time.sleep(wait_time) print "%s finished!" % self.name if __name__=="__main__": threads = [] for i in range(5): t = MyThread() t.start() threads.append(t) print 'main thread is waitting for exit...' for t in threads: t.join(1) print 'main thread finished!'
执行结果:
Thread-1 will wait 3 seconds
Thread-2 will wait 4 seconds
Thread-3 will wait 1 seconds
Thread-4 will wait 5 seconds
Thread-5 will wait 3 seconds
main thread is waitting for exit...
Thread-3 finished!
Thread-1 finished!
Thread-5 finished!
main thread finished!
Thread-2 finished!
Thread-4 finished!
对于sleep时间过长的线程(这里是2和4),将不被等待。
后台线程
默认情况下,主线程在退出时会等待所有子线程的结束。如果希望主线程不等待子线程,而是在退出时自动结束所有的子线程,就需要设置子线程为后台线程(daemon)。方法是通过调用线程类的setDaemon()方法。如下:import threading import random import time class MyThread(threading.Thread): def run(self): wait_time=random.randrange(1,10) print "%s will wait %d seconds" % (self.name, wait_time) time.sleep(wait_time) print "%s finished!" % self.name if __name__=="__main__": print 'main thread is waitting for exit...' for i in range(5): t = MyThread() t.setDaemon(True) t.start() print 'main thread finished!'
执行结果:
main thread is waitting for exit...
Thread-1 will wait 3 seconds
Thread-2 will wait 3 seconds
Thread-3 will wait 4 seconds
Thread-4 will wait 7 seconds
Thread-5 will wait 7 seconds
main thread finished!
可以看出,主线程没有等待子线程的执行,而直接退出。
小结
join()方法使得线程可以等待另一个线程的运行,而setDaemon()方法使得线程在结束时不等待子线程。join和setDaemon都可以改变线程之间的运行顺序。相关文章推荐
- python log
- python多线程编程(7):线程间通信
- Python自省(反射)指南
- 使用python检测一个设备是否ping的通
- QGIS python开发手册-加载工程文件
- Python windows 下 入门操作
- Python 中配置文件处理详解--ConfigParser,有了它就可随意操作配置文件了
- 初窥Python(三)——python版本升级及ipython的安装使用
- python中的map、filter、reduce函数
- Python运算符
- python format 大全
- python StringIo,Base64,上传文件
- python 的日志logging模块
- 【Python】【3】Python之——从HelloWorld开始(四则运算,简单函数以及简单模块)
- 使用Python-Diamond收集监控数据
- 【Python】 [基础] list和tuple
- Python将excel导入到mysql中
- 举例详解Python中yield生成器的用法
- python多线程编程(5): 条件变量同步
- Python学习笔记04