上一篇文章最后只是簡單介紹了start()方法和run()方法,這篇文章再詳細地看下start()和run()的區別。
在實例調用的函數中加入打印當前線程的名字,分別用start()方法和run()方法啟動線程檢查有什么區別:
start()方法:
import threading
import time
def worker():
count = 1
while True:
if count >= 6:
break
time.sleep(1)
count += 1
print("thread name = {}".format(threading.current_thread().name))#當前線程名
t = threading.Thread(target=worker,name="MyThread")
t.start()
print("===end===")
運行結果:
===end===
thread name = MyThread #
thread name = MyThread
thread name = MyThread
thread name = MyThread
thread name = MyThread
從上面例子中打印的線程名字來看,使用start()方法啟動的線程名是我們定義線程對象時設置的name="MyThread"的值,如果沒有設置name參數值,則會打印系統分配的Thread-1,Thread-2...這樣的名稱。
run()方法:
import threading
import time
def worker():
count = 1
while True:
if count >= 6:
break
time.sleep(1)
count += 1
print("thread name = {}".format(threading.current_thread().name))
t = threading.Thread(target=worker,name="MyThread")
t.run()
print("===end===")
運行結果:
thread name = MainThread #
thread name = MainThread
thread name = MainThread
thread name = MainThread
thread name = MainThread
===end===
上面例子中,使用的是用run()方法啟動線程,它打印的線程名是MainThread,也就是主線程。
再看下多線程時的例子:
start():
import threading
import time
def worker():
count = 1
while True:
if count >= 6:
break
time.sleep(1)
count += 1
print("thread name = {}, thread id = {}".format(threading.current_thread().name,threading.current_thread().ident))
t1 = threading.Thread(target=worker,name="t1")
t2 = threading.Thread(target=worker,name='t2')
t1.start()
t2.start()
print("===end===")
運行結果:
===end===
thread name = t1, thread id = 6032
thread name = t2, thread id = 880
thread name = t1, thread id = 6032
thread name = t2, thread id = 880
thread name = t2, thread id = 880
thread name = t1, thread id = 6032
thread name = t1, thread id = 6032
thread name = t2, thread id = 880
thread name = t2, thread id = 880
thread name = t1, thread id = 6032
上面例子中,start()方法啟動了兩個新的子線程並交替運行,每個子進程ID也不同。
run():
import threading
import time
def worker():
count = 1
while True:
if count >= 6:
break
time.sleep(1)
count += 1
print("thread name = {}, thread id = {}".format(threading.current_thread().name,threading.current_thread().ident))
t1 = threading.Thread(target=worker,name="t1")
t2 = threading.Thread(target=worker,name='t2')
t1.run()
t2.run()
print("===end===")
運行結果:
thread name = MainThread, thread id = 2000
thread name = MainThread, thread id = 2000
thread name = MainThread, thread id = 2000
thread name = MainThread, thread id = 2000
thread name = MainThread, thread id = 2000
thread name = MainThread, thread id = 2000
thread name = MainThread, thread id = 2000
thread name = MainThread, thread id = 2000
thread name = MainThread, thread id = 2000
thread name = MainThread, thread id = 2000
===end===
上面例子中,兩個子線程都用run()方法啟動,但卻是先運行t1.run(),運行完之后才按順序運行t2.run(),兩個線程都工作在主線程,沒有啟動新線程,因此,run()方法僅僅是普通函數調用。
一個進程中至少有一個線程,並作為程序的入口,這個線程就是主線程。
一個進程至少有一個主線程,其它線程稱為工作線程。
總結:
好了,從上面四個小例子,我們可以總結出:
- start() 方法是啟動一個子線程,線程名就是我們定義的name
- run() 方法並不啟動一個新線程,就是在主線程中調用了一個普通函數而已。
因此,如果你想啟動多線程,就必須使用start()方法。
