python线程的一些疑问
2016-04-14 09:42
453 查看
转自: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都可以改变线程之间的运行顺序。
本人已在github上用Jekyll建立了新的博客:http://thinkinside.tk/,本站文章会陆续迁移过去
相关文章推荐
- Python教程1-7
- python非阻塞启动进程
- python 小模块--platform
- python 牛顿迭代小游戏
- Show me the code之Python练习册 Q8~9 html解析
- Show me the code之Python练习册 Q4~7
- Show me the code之Python练习册 Q1~3 优惠券
- python中if __name__ == '__main__': 的解析
- python读txt文件的编码问题
- python基本数据类型-数字
- 开始写blog记录下学习python的过程
- How is map() implemented internally in Python?
- Python语言进行机器学习的开源项目
- 随机验证码生成(python实现)
- python利用wmi修改IP、DNS
- Python爬虫爬验证码实现功能详解
- 十个python程序小技巧
- python 爬虫试手 requests+BeautifulSoup
- python函数
- Python中os及os.path的相关方法