這篇文章主要介紹threading模塊中的主類Thread的一些主要方法,實例代碼如下:
# !/usr/bin/python3
# coding: utf-8
import threading
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("I am %s" % self.name)
if __name__ == "__main__":
for i in range(0, 5):
my_thread = MyThread()
my_thread.start()
1、name相關
你可以爲每一個thread指定name,默認的是 Thread-Number 形式的,如上述實例代碼打印出的一樣:
I am Thread-1
I am Thread-2
I am Thread-3
I am Thread-4
I am Thread-5
當然你可以指定每一個thread的name,這個通過setName方法,代碼:
# !/usr/bin/python3
# coding: utf-8
import threading
class MyThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.setName(name)
def run(self):
print("I am %s" % self.name)
if __name__ == "__main__":
for i in range(0, 5):
name = "new-%s" % i
my_thread = MyThread(name)
my_thread.start()
運行結果如下:
I am new-0
I am new-1
I am new-2
I am new-3
I am new-4
2、join方法
join方法是用來阻塞當前上下文,直至該線程運行結束
3、setDaemon方法
當我們在程序運行中,執行一個主線程,如果主線程又創建一個子線程,主線程和子線程就分兵兩路,當主線程完成想退出時,會檢驗子線程是否完成。如果子線程未完成,則主線程會等待子線程完成後再退出。但是有時候我們需要的是,只要主線程完成了,不管子線程是否完成,都要和主線程一起退出,這時就可以用setDaemon方法,並設置其參數爲True。