簡體   English   中英

python - 多線程 - join()方法

[英]python - multithreading — join() method

import threading, time

class test(threading.Thread):                 

    def __init__(self,name,delay):
        threading.Thread.__init__(self)
        self.name = name
        self.delay = delay

    def run(self):
        c = 0
        while True:
            time.sleep(self.delay)            
            print 'This is thread %s on line %s' %(self.name,c)
            c = c + 1 
            if c == 15:
                print 'End of thread %s' % self.name
                break

one = test('one', 1).start()
two = test('two', 3).start()

one.join()
two.join()

print 'End of main'

問題:無法使join()方法正常工作,給出以下錯誤:

Traceback (most recent call last)line 29, in <module> join() NameError: name 'join' is not defined

如果我刪除:

one.join
two.join

代碼工作得非常好。

我想打印最后一行,

print 'End of main'

兩個線程結束后。 我似乎無法理解為什么join()不是這兩個實例的屬性?

one = test('one', 1).start()
two = test('two', 3).start()

你的問題是start()沒有return self onetwo不是線程。 它們是None或者start()的返回值實際上是什么。

這有效:

one = test('one', 1)
one.start()
two = test('two', 3)
two.start()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM