Python-并行运行线程,而不是顺序运行

时间:2018-09-30 21:19:36

标签: python python-3.x multithreading python-multithreading

代码:

from threading import Thread
import time

def main():
    print([threadID])
    time.sleep(5)
    pass

if __name__ == '__main__':
    threadID = 0
    while threadID < 5:
        main()
        threadID +=1

当前,它运行第一个线程,然后一旦完成,就开始下一个线程。

如何使所有线程同时启动?

1 个答案:

答案 0 :(得分:0)

我觉得有点愚蠢,但从未真正调用过线程...

代码:

from threading import Thread
import time

def main():
    print([threadID])
    time.sleep(5)
    pass

if __name__ == '__main__':
    threadID = 0
    while threadID < 5:
        t = Thread(target=main)
        t.start()
        threadID +=1