美文网首页
Threading join()和setDeamon()

Threading join()和setDeamon()

作者: butters001 | 来源:发表于2021-02-19 11:07 被阅读0次

    join(timeout=None)
    在主线程A中创建子线程B,执行B.join(),则主线程将在join处阻塞至子线程B结束后(或超时),主线程才继续向下运行

    # 无join
    import threading
    import time
    
    class MyThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
    
        def run(self):
            time.sleep(5)
            print("This is " + self.getName())
    
    if __name__ == "__main__":
        t1 = MyThread()
        t1.start()
        print("I am the father thread.")
    
    """
    结果: 主线程和子线程同时执行,主线程等待所有子线程退出后,主线程再退出。
    I am the father thread.
    This is Thread-1
    """
    
    # 有join
    import threading
    import time
    
    class MyThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
    
        def run(self):
            time.sleep(5)
            print("This is " + self.getName())
    
    if __name__ == "__main__":
        t1 = MyThread()
        t1.start()
        t1.join()
        print("I am the father thread.")
    
    """
    结果 主线程在join处阻塞,阻塞至子线程t1退出后,主线程再继续向下执行。
    This is Thread-1
    I am the father thread.
    """
    

    setDaemon(True/False)
    默认为False,即上面无join模式,主线程会等待子线程结束。
    如果设置为True,主线程执行完后直接退出程序,不管子线程的执行状况。
    注意:setDaemon要在start()之前设置

    import threading
    import time
    
    class MyThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
    
        def run(self):
            time.sleep(5)
            print("This is " + self.getName())
    
    if __name__ == "__main__":
        t1 = MyThread()
        t1.setDaemon(True)
        t1.start()
        print("I am the father thread.")
    
    """
    结果:设置守护线程,则主线程不再等待子线程执行完,主线程执行完后直接退出程序,不管子线程的执行状况。
    I am the father thread.
    """
    

    相关文章

      网友评论

          本文标题:Threading join()和setDeamon()

          本文链接:https://www.haomeiwen.com/subject/artaxltx.html