2012-02-13 110 views
2

好吧,我寫了一個小急速試圖知道如何使用python線程。 但奇怪的是,下面的代碼只是快速退出沒有預期的輸出。 是否因爲我不應該通過過濾run()方法來產生線程?Python線程無法正常工作

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

回答

5

您需要啓動線程,使之能做些什麼:(爲什麼?)

t = mythread() 
t.start() 

如果你懶得在構造函數接受target參數,你不應該忽略此參數。也許你想將它傳遞給Thread構造函數。 (爲什麼?)

+0

我想我已經在run()方法中開始了。你是對的!我發現run()方法中的spawn線程現在很愚蠢。謝謝Marnach〜 – 2012-02-13 12:07:13

+0

當你不啓動父線程時,它不會有機會啓動子線程。 – 2012-02-13 12:09:39

1

當您編寫mythread()時,您將實例化對象。默認構造函數將被調用,所以__init__()將被執行。

你的構造函數沒有任何啓動線程的指令。