Python中如何创建并启动多个线程
发布时间:2024-01-03 16:45:00
在Python中,可以使用threading模块来创建多个线程,并通过start()方法启动这些线程。以下是在Python中创建并启动多个线程的示例代码:
import threading
import time
# 定义一个线程的类
class MyThread(threading.Thread):
def __init__(self, name, delay):
threading.Thread.__init__(self)
self.name = name
self.delay = delay
# 重写run()方法,定义线程要执行的任务
def run(self):
print(f"线程 {self.name} 正在执行")
time.sleep(self.delay)
print(f"线程 {self.name} 执行完毕")
# 创建多个线程
thread1 = MyThread("Thread 1", 2)
thread2 = MyThread("Thread 2", 3)
thread3 = MyThread("Thread 3", 1)
# 启动多个线程
thread1.start()
thread2.start()
thread3.start()
# 等待所有线程执行完毕
thread1.join()
thread2.join()
thread3.join()
print("所有线程执行完毕")
上述代码中,我们首先定义了一个继承自threading.Thread的类MyThread,在该类中重写了run()方法,并定义了线程要执行的任务。然后,我们创建了三个线程thread1、thread2和thread3,并传入不同的线程名和延迟时间。最后,调用start()方法分别启动这三个线程。在主线程中,我们使用join()方法来等待所有子线程执行完毕,最后输出“所有线程执行完毕”。
运行以上代码,输出结果类似于:
线程 Thread 1 正在执行 线程 Thread 3 正在执行 线程 Thread 3 执行完毕 线程 Thread 2 正在执行 Thread 3 执行完毕 线程 Thread 1 执行完毕 线程 Thread 2 执行完毕 所有线程执行完毕
可以看到,多个线程同时执行,且执行顺序不确定,但主线程在子线程执行完毕后才会继续执行。
