Skip to main content
 首页 » 编程设计

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

2024年08月27日30think

下面的代码对我有用,问题是每个线程都必须等到抛出结束或者至少我有这样的看法,因为当我放置 sleep (10)时,等待时间被指示然后连续。

我希望的是 haul 线程不必等待内部代码运行。

这是我的代码(示例):

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() 

提前致谢。

请您参考如下方法:

使用 2 个 for 循环:1 个启动线程,一个等待线程:

# create all threads 
ts = [MyThread(i) for i in range(10)] 
 
# start all threads 
for t in ts: 
    t.start() 
 
# wait for all threads 
for t in ts: 
    t.join()