2012-10-06 70 views
1
import threading, time 

class test(threading.Thread):     

    def __init__(self,name,delay): 
     threading.Thread.__init__(self) 
     self.name = name 
     self.delay = delay 

    def run(self): 
     c = 0 
     while True: 
      time.sleep(self.delay)    
      print 'This is thread %s on line %s' %(self.name,c) 
      c = c + 1 
      if c == 15: 
       print 'End of thread %s' % self.name 
       break 

one = test('one', 1).start() 
two = test('two', 3).start() 

one.join() 
two.join() 

print 'End of main' 

問題:無法獲得參加()方法才能正常工作,提供了以下錯誤:蟒蛇 - 多線程 - join()方法

Traceback (most recent call last)line 29, in <module> join() NameError: name 'join' is not defined 

如果我刪除:

one.join 
two.join 

代碼工作得很好。

我想打印的最後一行,

print 'End of main' 

兩個線程都結束之後。我似乎無法理解爲什麼join()不是這兩個實例的屬性?

+0

您intendation擰。 –

+0

抱歉 - 新手在這裏。我試過 – mrdigital

+0

我的意思是在你的文章中。我認爲你的程序看起來不一樣,否則你不會走得那麼遠。 –

回答

4
one = test('one', 1).start() 
two = test('two', 3).start() 

您的問題是start()沒有做一個return selfonetwo不是線程。他們是None或任何返回值start()實際上是。

這工作:

one = test('one', 1) 
one.start() 
two = test('two', 3) 
two.start() 
+1

那次你打敗了我;) –

+0

你們都打敗了我。 SO說23秒! – rbanffy

+0

太棒了!沒有意識到這與RETURN更重要,我更關注代碼縮短。無論如何,謝謝 – mrdigital