Python run()函式和start()函式的比較和差別
run() 方法並不啟動一個新執行緒,就是在主執行緒中呼叫了一個普通函式而已。 start() 方法是啟動一個子執行緒,執行緒名就是自己定義的name。 因此,如果你想啟動多執行緒,就必須使用start()方法。
請看例項:(原始碼) 1 使用run()方法啟動執行緒,它列印的執行緒名是MainThread,也就是主執行緒。 import threading,time
def worker(): count = 1 while True: if count >= 4: break time.sleep(1) count += 1 print(“thread name = {}”.format(threading.current_thread().name))
print(“Start Test run()”) t1 = threading.Thread(target=worker, name=“MyTryThread”) t1.run()
print(“run() test end”)
執行結果: Start Test run() thread name = MainThread thread name = MainThread thread name = MainThread run() test end 2 使用start()方法啟動的執行緒名是我們定義執行緒物件時設定的name="MyThread"的值,如果沒有設定name引數值,則會列印系統分配的Thread-1,Thread-2…這樣的名稱。
import threading,time
def worker(): count = 1 while True: if count >= 4: break time.sleep(2) count += 1 print(“thread name = {}”.format(threading.current_thread().name)) # 當前執行緒名
print(“Start Test start()”) t = threading.Thread(target=worker, name=“MyTryThread”) t.start() t.join()
print(“start() test end
3 兩個子執行緒都用run()方法啟動,但卻是先執行t1.run(),執行完之後才按順序執行t2.run(),兩個執行緒都工作在主執行緒,沒有啟動新執行緒,thread ID都是一樣的,因此,run()方法僅僅是普通函式呼叫。 import threading,time
def worker(): count = 1 while True: if count >= 4: break time.sleep(2) count += 1 print(“thread name = {}, thread id = {}”.format(threading.current_thread().name, threading.current_thread().ident))
print(“Start Test run()”) t1 = threading.Thread(target=worker, name=“t1”) t2 = threading.Thread(target=worker, name=‘t2’)
t1.run() t2.run()
print(“run() test end”) 執行結果: Start Test run() thread name = MainThread, thread id = 3920 thread name = MainThread, thread id = 3920 thread name = MainThread, thread id = 3920 thread name = MainThread, thread id = 3920 thread name = MainThread, thread id = 3920 thread name = MainThread, thread id = 3920 run() test end
4 使用start()方法啟動了兩個新的子執行緒並交替執行,每個子程序ID也不同。
import threading,time
def worker(): count = 1 while True: if count >= 4: break time.sleep(2) count += 1 print(“thread name = {}, thread id = {}”.format(threading.current_thread().name, threading.current_thread().ident))
print(“Start Test start()”) t1 = threading.Thread(target=worker, name=“MyTryThread1”) t2 = threading.Thread(target=worker, name=“MyTryThread2”) t1.start() t2.start() t1.join() t2.join() print(“start() test end”)
執行結果: Start Test start() thread name = MyTryThread1, thread id = 4628 thread name = MyTryThread2, thread id = 872 thread name = MyTryThread1, thread id = 4628 thread name = MyTryThread2, thread id = 872 thread name = MyTryThread1, thread id = 4628 thread name = MyTryThread2, thread id = 872 start() test end