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