如何并行或多线程执行代码

2024-05-08 17:22:17 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码适用于我,问题是每个线程必须等到抛出结束或者至少是我的感知,因为当我进入睡眠(10)时,等待时间被指示,然后是连续的。你知道吗

我所希望的是,在不必等待内部代码运行的情况下调用线程。你知道吗

这是我的代码(示例):

import threading
from time import sleep

class MyThread(threading.Thread):
    def __init__(self, num):
        threading.Thread.__init__(self)
        self.num = num

    def run(self):
        print "I'm the thread", self.num
        sleep(10)
        print "I'm the thread, after 10 seg"


print "I'm the main thread"
for i in range(0, 10):
    t = MyThread(i)
    t.start()
    t.join()

提前谢谢。你知道吗


Tags: the代码importselfinitdefsleep线程