2013-06-05 116 views
0

我正在嘗試使用我正在處理的項目的線程。這裏是我用作測試的代碼Python線程。爲什麼我一次只能運行一個線程

import threading 


class one(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 
     while 1: 
      print "one" 


class two(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 
     while 1: 
      print "two" 

threads = [] 

one = one() 
two = two() 

one.start() 
two.start() 


threads.append(one) 
threads.append(two) 

for t in threads: 
    t.join() 

問題是隻有第一類運行。你能看到我的代碼有問題嗎?

+1

出於好奇,你從哪裏得到了重寫'__init__'的想法? – delnan

+0

來自這篇文章http://www.tutorialspoint.com/python/python_multithreading.htm – PrestonDocks

+0

碰巧我已經解決了這個問題。我沒有在每個類中使用所需的def run(self):方法。 – PrestonDocks

回答

3

你必須重寫run方法,而不是__init__

class one(threading.Thread): 
    def run(self): 
     while 1: 
      print "one" 

這種方法是什麼是在不同的線程中執行,而one = one()開始在同一個線程無限循環的對象被創建。

覆蓋,如果你想傳遞一個參數__init__在新的線程中使用,例如:

class NumberedThread(threading.Thread): 
    def __init__(self, number): 
     threading.Thread.__init__(self) 
     self.number = number 

    def run(self): 
     while 1: 
      print self.number 

NumberedThread("one").start() 
NumberedThread("two").start() 
1

你已經把一個無限循環在你的線程構造函數。你的第一個「線程」從來沒有從它的構造函數中解脫出來,所以試圖創建它的代碼只是坐在那裏等待創建對象。因此,您實際上並沒有多線程處理任何東西:您在主線程中剛剛獲得了無限循環。

覆蓋run而不是__init__,你應該全部設置。

class one(threading.Thread): 
    def run(self): 
     while 1: 
      print "one" 


class two(threading.Thread): 
    def run(self): 
     while 1: 
      print "two"