今天学到python多线程这块,想显示当前线程是主线程还是子线程.网上一搜,有个方法叫
1 threading.current().name
但是发现,同样的threading.current_thread()后面不仅仅有.name属性,而且还有.getName()方法.但是
这2个写法最后得出的结果却是一样的.
那么,2者区别在哪里呢?
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' 来改变它。
最终演示代码:
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))
代码结果:
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