每一个 Thread 都有一个 name 的属性,代表的就是线程的名字,这个可以在构造方法中赋值。假如在构造方法中没有个 name 赋值的话,默认就是 “Thread-N” 的形式,N 是数字。通过 thread.current_thread() 方法可以返回线程本身,然后就可以访问它的 name 属性。
import threading
import time
def test():
for i in range(5):
print(threading.current_thread().name+' test ',i)
time.sleep(1)
thread = threading.Thread(target=test)
thread.start()
for i in range(5):
print(threading.current_thread().name+' main ', i)