多线程的创建方式
时间: 2023-07-27 17:06:08 浏览: 58
在Python中,创建多线程有两种方式:
1. 继承Thread类,重写run()方法:
```python
import threading
class MyThread(threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
print("Starting " + self.name)
# 执行线程的操作
print("Exiting " + self.name)
# 创建线程
thread1 = MyThread(1, "Thread-1")
thread2 = MyThread(2, "Thread-2")
# 开启线程
thread1.start()
thread2.start()
```
2. 使用函数式编程的方式创建线程:
```python
import threading
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
# 创建线程
thread1 = threading.Thread(target=print_time, args=("Thread-1", 1, 5))
thread2 = threading.Thread(target=print_time, args=("Thread-2", 2, 5))
# 开启线程
thread1.start()
thread2.start()
```
以上两种方式都可以创建多线程,只是实现方式不同。使用继承Thread类的方式更加面向对象,可以使用类的成员变量和方法;使用函数式编程的方式则更加灵活,可以将线程函数作为参数传递。