python - 如何在 Python 中与线程并行运行两个函数?
问题描述
我想并行运行两个函数,它们并行打印两个列表。但我得到的是一个列表,在另一个列表完成后打印。
我已经尝试了以下代码。
import threading
import time
def fun1():
testz=['z','y','x','w','v','u','t']
for j in testz:
print (j)
time.sleep(1)
def fun2():
test=['a','b','c','d','e','f','g']
for i in test:
print (i)
time.sleep(1)
thread1 = threading.Thread(target=fun1())
thread2 = threading.Thread(target=fun2())
thread1.start()
time.sleep(0.5)
thread2.start()
thread1.join()
thread2.join()
我期望的结果是:
z
a
y
b
x
c
w
d
v
e
u
f
t
g
但我得到的是:
z
y
x
w
v
u
t
a
b
c
d
e
f
g
这似乎两个线程一个接一个地运行。
解决方案
问题是您在主线程中运行函数,而不是在子线程中。您首先调用函数,然后将返回的值作为线程目标。您的代码应该是:
thread1 = threading.Thread(target=fun1)
thread2 = threading.Thread(target=fun2)
然后你会得到预期的结果。
推荐阅读
- node.js - 保留 .git/HEAD
- bazel - 查询 Bazel 缓存?
- reactjs - Reactjs - setState() 使应用程序的所有文本闪烁
- python - 使用 Python 计算第一列中填充的单元格数
- mbedtls - 使用 libmbedtls-dev 安装 mbed TLS
- php - PHP继承:如何从父对象引用子对象?
- javascript - 如何测试 AWS S3 上是否存在存储桶
- python-3.x - IndexError: index 2 is out of bounds for axis 0 with size 2 // Python 3 Qlearning
- java - 面板的油漆组件不绘制双点值
- python-2.7 - Spark Dataframe 在 EMR 上加载 500k 文件