爲什麼此代碼沒有「行爲」線程化? (請參閱輸出)。Python線程代碼不起作用線程
import time
from threading import Thread
def main():
for nums in [range(0,5), range(5,10)]:
t = Spider(nums)
t.start()
print 'started a thread'
t.join()
print "done"
class Spider(Thread):
def __init__(self, nums):
Thread.__init__(self)
self.nums = nums
def run(self): # this is an override
for num in self.nums:
time.sleep(3) # or do something that takes a while
print 'finished %s' % (num,)
if __name__ == '__main__':
main()
輸出:
started a thread
finished 0
finished 1
finished 2
finished 3
finished 4
started a thread
finished 5
finished 6
finished 7
finished 8
finished 9
done
因此,您可能希望將線程引用存儲在列表中,並將它們連接到循環之外。 – 2011-02-06 14:46:12