今天學到python多線程這塊,想顯示當前線程是主線程仍是子線程.網上一搜,有個方法叫python
1 threading.current().name
可是發現,一樣的threading.current_thread()後面不單單有.name屬性,並且還有.getName()方法.可是多線程
這2個寫法最後得出的結果倒是同樣的.ide
那麼,2者區別在哪裏呢?ui
1 import threading 2 import time 3 4 def run(arg): 5 print("running sub thread...{}".format(threading.current_thread())) 6 time.sleep(3) 7 8 if __name__ == "__main__": 9 t1 = threading.Thread(target=run,args=("t1",)) 10 t1.start() 11 print("mian Thread...{}".format(threading.current_thread().getName())) 12 print("mian Thread...{}".format(threading.current_thread().name)) 13 14 t2 = threading.Thread()
name 是當前線程的屬性, getName 是當前線程的方法。
儘管 threading.current_thread().name 和 threading.current_thread().getName() 的結果同樣,可是徹底不是同一種東西呀, 例如經過 threading.current_thread().name = 'thread_python' 來改變它。spa
最終演示代碼:線程
1 import threading 2 import time 3 4 def run(arg): 5 print("running sub thread...{}".format(threading.current_thread())) 6 threading.current_thread().name="xurui_python" 7 print("sub1 Thread...{}".format(threading.current_thread().getName())) 8 print("sub2 Thread...{}".format(threading.current_thread().name)) 9 time.sleep(3) 10 11 if __name__ == "__main__": 12 t1 = threading.Thread(target=run,args=("t1",)) 13 t1.start() 14 print("mian1 Thread...{}".format(threading.current_thread().getName())) 15 print("mian2 Thread...{}".format(threading.current_thread().name))
代碼結果:3d
1 running sub thread...<Thread(Thread-1, started 23296)> 2 mian1 Thread...MainThread 3 mian2 Thread...MainThread 4 sub1 Thread...xurui_python 5 sub2 Thread...xurui_python