Python多線程編程(8): 線程的合并和後台線程

來源:互聯網
上載者:User

【轉自】暱稱:Holbrook  http://www.cnblogs.com/holbrook/archive/2012/02/25/2368231.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都可以改變線程之間的運行順序。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.