在Python中,多線程是一種并發編程技術,它允許你同時運行多個任務
threading
模塊。這個模塊提供了用于多線程編程的類和方法。import threading
def print_numbers():
for i in range(10):
print(i)
def print_letters():
for letter in 'abcdefghij':
print(letter)
threading.Thread
類,并將函數名作為參數傳遞給它。thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
start()
方法啟動線程。這將使得線程開始執行目標函數。thread1.start()
thread2.start()
join()
方法。這將阻塞主線程,直到所有子線程完成。thread1.join()
thread2.join()
import threading
def print_numbers():
for i in range(10):
print(i)
def print_letters():
for letter in 'abcdefghij':
print(letter)
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
運行此腳本,你將看到數字和字母被交錯打印。這表明兩個線程已經并發執行。請注意,由于多線程的性質,輸出順序可能會有所不同。