请问,如何在 Python 中实现多线程编程?
时间: 2023-05-17 07:03:51 浏览: 141
在 Python 中,可以使用 threading 模块来实现多线程编程。具体步骤如下:
1. 导入 threading 模块:import threading
2. 定义一个线程类,继承自 threading.Thread 类,并重写 run() 方法。
3. 创建线程对象:t = MyThread()
4. 启动线程:t.start()
以下是一个简单的示例代码:
import threading
class MyThread(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print("Starting " + self.name)
print_time(self.name, self.counter, 5)
print("Exiting " + self.name)
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
# 创建新线程
thread1 = MyThread(1, "Thread-1", 1)
thread2 = MyThread(2, "Thread-2", 2)
# 开启新线程
thread1.start()
thread2.start()
print("Exiting Main Thread")
阅读全文