本地的天津网站建设,微信开发者工具打印1n的所有值,苏州网站建设老板,传统媒体网站建设From: http://www.cnblogs.com/holbrook/archive/2012/03/21/2410120.html 线程的合并
python的Thread类中还提供了join()方法#xff0c;使得一个线程可以等待另一个线程执行结束后再继续运行。这个方法还可以设定一个timeout参数#xff0c;避免无休止的等待。因为两个线…From: http://www.cnblogs.com/holbrook/archive/2012/03/21/2410120.html 线程的合并
python的Thread类中还提供了join()方法使得一个线程可以等待另一个线程执行结束后再继续运行。这个方法还可以设定一个timeout参数避免无休止的等待。因为两个线程顺序完成看起来象一个线程所以称为线程的合并。一个例子 import threadingimport randomimport timeclass MyThread(threading.Thread): def run(self): wait_timerandom.randrange(1,10) print %s will wait %d seconds % (self.name, wait_time) time.sleep(wait_time) print %s finished! % self.nameif __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 threadingimport randomimport timeclass MyThread(threading.Thread): def run(self): wait_timerandom.randrange(1,10) print %s will wait %d seconds % (self.name, wait_time) time.sleep(wait_time) print %s finished! % self.nameif __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都可以改变线程之间的运行顺序。