All*_*uin 2 python multithreading
好吧,我写了一个小snappet试图知道如何使用python线程.但奇怪的是,以下代码在没有预期输出的情况下快速退出.是因为我不应该通过覆盖run()方法来生成线程吗?
import threading
from time import sleep
class mythread(threading.Thread):
def __init__(self,target=None,thread_num=5):
threading.Thread.__init__(self,target=None)
self.thn = thread_num
def run(self):
for i in range(self.thn):
t = threading.Thread(target=self.myfunc)
t.start()
t.join()
myfunc(self.thn)
def myfunc(num):
print num,'\tI am doing sth.'
sleep(0.5)
print num,'\tI have done it.'
mythread()
Run Code Online (Sandbox Code Playgroud)
您需要启动该线程以使其实际执行某些操作:
t = mythread()
t.start()
Run Code Online (Sandbox Code Playgroud)
如果你懒得target
在构造函数中接受一个参数(为什么?),你不应该忽略这个参数.也许你想把它传递给Thread
构造函数.(为什么?)