日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python多线程编程(8):线程的合并和后台线程

發布時間:2023/12/9 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python多线程编程(8):线程的合并和后台线程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

From: http://www.cnblogs.com/holbrook/archive/2012/03/21/2410120.html

?

線程的合并

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多线程编程(8):线程的合并和后台线程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。