在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()
运行此脚本,你将看到数字和字母被交错打印。这表明两个线程已经并发执行。请注意,由于多线程的性质,输出顺序可能会有所不同。