对Python线程中join步骤的疑问

对Python线程中join方法的疑问
代码如下:
import threading
import time
from random import randint

class MyThread(threading.Thread):
    def __init__(self,id):
        threading.Thread.__init__(self)
        self.id=id
    def run(self):
        x = randint(1,10)
        time.sleep(x)
        print "Thread %d sleeped %d sec." % (self.id, x)

def main():
    threads = []
    for i in range(10):
        threads.append(MyThread(i))
    
    for t in threads:
        t.start()
    for t in threads:
        t.join()

    print "main done!"

if __name__=="__main__":
    main()

结果:
Thread 4 sleeped 1 sec.
Thread 5 sleeped 1 sec.
Thread 9 sleeped 1 sec.
Thread 0 sleeped 2 sec.
Thread 3 sleeped 4 sec.
Thread 7 sleeped 6 sec.
Thread 8 sleeped 6 sec.
Thread 1 sleeped 7 sec.
Thread 2 sleeped 8 sec.
Thread 6 sleeped 8 sec.
main done!

在main()里执行t.join(), 我的理解应该是main所在的线程挂起,直到t执行完后再执行main.
当第一个t.join()后,main挂起,执行”Thread 0“. 但为什么for循环里的't.join()'语句在‘Thread 0’结束前就又执行了?
‘t.join()’在main里,应该是main的一部分。为什么它没有被挂起,还是照常执行?
而 print "main done!", 与main一起挂起了,直到Thead 0-9都结束后才执行?

------解决方案--------------------
引用:
在main()里执行t.join(), 我的理解应该是main所在的线程挂起,直到t执行完后再执行main.

确实是这样,见下面代码运行的输出.
引用:
当第一个t.join()后,main挂起,执行”Thread 0“. 但为什么for循环里的't.join()'语句在‘Thread 0’结束前就又执行了?

你怎么知道"for循环里的't.join()'语句在‘Thread 0’结束前就又执行了"?如果for循环继续执行了,"main done"应该是最先输出的,但你的运行结果不是这样.

下面的例子更明显一些:


import threading
import time
from random import randint

class MyThread(threading.Thread):
    def __init__(self,id):
        threading.Thread.__init__(self)
        self.id=id
    def run(self):
        x = randint(1,10)
        time.sleep(x)
        print "Thread %d sleeped %d sec." % (self.id, x)

def main():
    threads = []
    for i in range(10):
        threads.append(MyThread(i))
    
    for t in threads:
        t.start()
    for t in threads:
        print "waiting for thread:", t.id
        t.join()
        print "thread", t.id, "ended."

    print "main done!"

if __name__=="__main__":
    main()


输出:


waiting for thread: 0
Thread 3 sleeped 1 sec.
Thread 5 sleeped 4 sec.
Thread 9 sleeped 6 sec.
Thread 0 sleeped 7 sec.
thread 0 ended.
waiting for thread: 1
Thread 8 sleeped 9 sec.
 Thread 6 sleeped 9 sec.
Thread 7 sleeped 9 sec.
Thread 1 sleeped 10 sec.
thread 1 ended.
waiting for thread: 2
Thread 4 sleeped 10 sec.
Thread 2 sleeped 10 sec.
thread 2 ended.
waiting for thread: 3
thread 3 ended.
waiting for thread: 4
thread 4 ended.
waiting for thread: 5
thread 5 ended.
waiting for thread: 6
thread 6 ended.
waiting for thread: 7
thread 7 ended.
waiting for thread: 8
thread 8 ended.
waiting for thread: 9
thread 9 ended.
main done!