Python线程代码不代表线程化

H2O*_*aCl 0 python multithreading

为什么这段代码"行为"没有线程?(请参阅输出.)

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()
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

Seb*_*olm 6

当你说t.join(),你告诉它等待线程结束.

这意味着,你要求它创建一个线程,启动它,然后在创建一个新线程之前等待线程结束.

如果您希望它采用多线程,则需要将join()s 移动到循环外部.

def main():
    # We will store the running threads in this
    threads = []
    # Start the threads
    for nums in [range(0,5), range(5,10)]:
        t = Spider(nums)
        t.start()
        print 'started a thread'
        threads.append(t)
    # All the threads have been started
    # Now we wait for them to finish
    for t in threads:
        t.join()
    print "done"
Run Code Online (Sandbox Code Playgroud)

也可以看看: