[英]Python Threading. Why can I only run one thread at a time
我正在為我正在研究的項目嘗試線程化。 這是我用作測試的代碼
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()
問題在於,只有第一堂課可以上課。 您能看到我的代碼有問題嗎?
您必須重寫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()
您已經在線程構造函數中放入了無限循環。 您的第一個“線程”甚至永遠都不會脫離其構造函數,因此,試圖創建該線程的代碼只是坐着等待對象的創建。 結果,您實際上並沒有對任何線程進行多線程處理:您在主線程中只有一個無限循環。
覆蓋run
而不是__init__
,您應該已經准備__init__
。
class one(threading.Thread):
def run(self):
while 1:
print "one"
class two(threading.Thread):
def run(self):
while 1:
print "two"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.