在 Python 中,你可以使用 threading 模块来创建和管理多线程。以下是一个简单的例子,演示如何使用多线程执行并行任务:
import threading
import time

# 定义一个简单的函数作为线程任务
def print_numbers():
    for i in range(5):
        time.sleep(1)
        print(f"Thread 1: {i}")

def print_letters():
    for letter in "ABCDE":
        time.sleep(1)
        print(f"Thread 2: {letter}")

# 创建两个线程
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)

# 启动线程
thread1.start()
thread2.start()

# 等待两个线程完成
thread1.join()
thread2.join()

print("Both threads have finished.")

在这个例子中,我们定义了两个简单的线程任务函数 print_numbers 和 print_letters,它们分别打印数字和字母。然后,我们创建了两个线程 thread1 和 thread2,并通过 start 方法启动它们。最后,通过 join 方法等待两个线程完成。

需要注意的是,Python 中的全局解释器锁 (GIL) 限制了在同一时刻只能有一个线程执行 Python 字节码。因此,在 CPU 密集型任务中,使用多线程可能并不会提高性能。但在 I/O 密集型任务中,多线程通常能够带来性能的提升。

如果你想要执行更多并行任务,也可以考虑使用 concurrent.futures 模块中的 ThreadPoolExecutor 或 ProcessPoolExecutor,它们提供了更高级的并发处理。


转载请注明出处:http://www.zyzy.cn/article/detail/13341/Python 基础