from threading import Thread
import time
print 'start of script'
class MyThread(Thread):
def run(self):
for i in xrange(10):
print 'thread->', '['+self.name+']', '('+str(i)+')'
time.sleep(2)
for i in range(3):
my_thread = MyThread()
my_thread.name = i
my_thread.start()
print 'end of script'
>>> ================================ RESTART ================================
>>>
start of script
thread->thread->thread->end of script
[0][1][2]
>>> (0)(0)(0)
thread->thread->thread-> [0][2][1] (1)(1)(1)
thread->thread-> thread-> [0] [2] [1] (2) (2)
(2)
thread-> thread->thread->[0] [2][1](3)
(3)(3)
thread-> thread->thread->[0] [2][1](4)
(4)(4)
thread-> thread->[0]thread-> [2](5)[1]
(5)(5)
thread-> [0]thread->thread-> (6)[2][1]
(6)(6)
thread-> thread->[0]thread-> [2](7)[1]
(7)(7)
thread-> thread->[0] thread-> [2] (8) [1]
(8)
(8)
thread->thread-> thread-> [0] [2] [1] (9) (9)
(9)
>>>
正如你可以看到我打印的“脚本的开始”,然后再执行多个线程,然后打印线程早期执行后的代码,为什么?
“脚本结束”不过,“脚本结束”被印我执行之后第一个线程,而不是在所有线程完成之后。我怎样才能防止这一点?
输出的混乱性质预期,实际上希望作为这些线程都应该是同时执行...
我在Windows 7是蟒蛇2.7 BTW ...
线程技术上何时开始执行?是不是当你调用.start(),但在你的例子中,它似乎只有当你调用.join()所有那些你已经“.start() - ed”我很困惑...... – MistahX 2011-06-12 17:11:39
一旦你调用start,线程就开始执行。它们与原始代码并行运行;连接调用只是确保它们在连接返回之前完成。 – Amber 2011-06-12 19:11:53