Python 中的线程不是同时运行的[重复]

问题描述 投票:0回答:1
from time import sleep
import threading


def sleep_and_print(duration, name):
    sleep(duration)
    print(name)

t1 = threading.Thread(target=sleep_and_print(2, "three second sleep"))
t2 = threading.Thread(target=sleep_and_print(1, "one second sleep"))

t1.start()
t2.start()

t1.join()
t2.join()

https://www.online-python.com/DcL2tujayw

对于上面的代码,我的期望是线程将异步启动,并且“一秒睡眠”将在“三秒睡眠”之前打印。然而,这并不是发生的顺序,它们似乎是同步运行的。

从我读过的文档中,我相信这应该可行,但我是Python新手。我尝试使用 ThreadPoolExecute 但也无法使其工作。预先感谢

python multithreading concurrency python-multithreading
1个回答
1
投票

您不是在线程中执行该函数,而是在

threading.Thread
声明中执行该函数。
target
应该是函数名称,参数应该以
args

形式发送
t1 = threading.Thread(target=sleep_and_print, args=(3, "three second sleep"))
t2 = threading.Thread(target=sleep_and_print, args=(1, "one second sleep"))

测试

for _ in range(10):
    t1 = threading.Thread(target=sleep_and_print, args=(1, 'thread 1'))
    t2 = threading.Thread(target=sleep_and_print, args=(1, 'thread 2'))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

输出

thread 1
thread 2
thread 1
thread 2
thread 2
thread 1
thread 2
thread 1
thread 1
thread 2
thread 2
thread 1
thread 2
thread 1
thread 2
thread 1
thread 1
thread 2
thread 1
thread 2
© www.soinside.com 2019 - 2024. All rights reserved.