写个python多线程
时间: 2023-10-13 07:06:36 浏览: 81
下面是一个简单的Python多线程示例,它创建两个线程并同时运行它们:
```python
import threading
def thread_function_1():
for i in range(5):
print("Thread 1 is running")
def thread_function_2():
for i in range(5):
print("Thread 2 is running")
if __name__ == "__main__":
# 创建两个线程
t1 = threading.Thread(target=thread_function_1)
t2 = threading.Thread(target=thread_function_2)
# 启动线程
t1.start()
t2.start()
# 等待线程结束
t1.join()
t2.join()
print("All threads have finished.")
```
在这个例子中,我们定义了两个线程函数(`thread_function_1`和`thread_function_2`),它们分别打印5次“Thread 1 is running”和“Thread 2 is running”。我们使用`threading.Thread`类创建了两个线程(`t1`和`t2`),并将它们的目标设置为我们定义的线程函数。然后,我们使用`start()`方法启动线程,使用`join()`方法等待线程结束。最后,我们打印一条消息表明所有线程都已经结束。
请注意,由于Python的全局解释器锁(GIL)限制,多线程并不总是能够提高程序的性能。在某些情况下,使用多进程可能更有效。
阅读全文
相关推荐













