我跑這個代碼爲什麼這10個線程總是輸出相同的線程名稱?
NUM = 0
def count():
global NUM
NUM += 1
time.sleep(1)
print(t.getName()+":"+"NUM is "+str(NUM))
for i in range(10):
t = threading.Thread(target=count)
t.start()
輸出是
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
Thread-10:NUM is 10
我知道爲什麼NUM始終是10,但爲什麼是線程的名字總是相同的?每個線程運行print(t.getName()+":"+"NUM is "+str(NUM))
; t
不應該是獲得CPU時間的線程?我認爲這個名字不應該是一樣的。
當我改變了這個
NUM = 0
def count():
global NUM
NUM += 1
name = t.getName()
time.sleep(1)
print(name+":"+"NUM is "+str(NUM))
for i in range(10):
t = threading.Thread(target=count)
t.start()
它的工作原理如我所料:
Thread-1:NUM is 10
Thread-3:NUM is 10
Thread-2:NUM is 10
Thread-4:NUM is 10
Thread-5:NUM is 10
Thread-7:NUM is 10
Thread-10:NUM is 10
Thread-9:NUM is 10
Thread-6:NUM is 10
Thread-8:NUM is 10
「t」在哪裏設置? –
't'是一個*外*變量。例如重複設置直到達到10。 –