当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Thread join()用法及代码示例


Python Thread.join() 方法

Thread.join() 方法是 Python 中线程模块的 Thread 类的内置方法。每当为任何 Thread 对象调用此方法时,它都会阻塞调用线程,直到调用其 join() 方法的线程终止(正常或通过未处理的异常)。

模块:

    from threading import Thread

用法:

    join(timeout=None)

参数:

  • timeout:它是一个可选参数,它以秒为单位指定操作的超时时间。它应该是一个浮点数。当超时参数丢失时,操作将阻塞,直到线程终止。

返回值:

这个方法的返回类型是<class 'NoneType'>,它什么都不返回。

例:

# Python program to explain the
# use of join() method in Thread class

import time
import threading

def thread_1(i):
    time.sleep(2)
    print('Value by Thread 1:', i)

def thread_2(i):
    time.sleep(5)
    print('Value by Thread 2:', i)

def thread_3(i):
    print('Value by Thread 3:', i)    

    
# Creating three sample threads 
thread1 = threading.Thread(target=thread_1, args=(1,))
thread2 = threading.Thread(target=thread_2, args=(2,))
thread3 = threading.Thread(target=thread_3, args=(3,))

# Running three thread object
thread1.start()
thread1.join()
thread2.start()
thread2.join()
thread3.start()
thread3.join()

print()
# Creating another 3 threads
thread4 = threading.Thread(target=thread_1, args=(1,))
thread5 = threading.Thread(target=thread_2, args=(2,))
thread6 = threading.Thread(target=thread_3, args=(3,))

thread4.start()
thread5.start()
thread6.start()
thread4.join()
thread5.join()
thread6.join()

输出

Value by Thread 1:1
Value by Thread 2:2
Value by Thread 3:3

Value by Thread 3:3
Value by Thread 1:1
Value by Thread 2:2

在最初的三个 Thread 对象中,我们首先创建了一个线程并等待它执行,然后加入到主线程中。因此,它们的打印顺序与调用顺序相同。

在接下来的三个 Thread 对象中,它们同时运行,因此根据它们应该执行的时间打印出来,

    time(thread3)<time(thread2)<time(thread1)

例:

# Python program to explain the
# use of join() method in Thread class 
# with timeout parameter defined

import time
import threading

def thread_1(i):
    time.sleep(2)
    print('Value by Thread 1:', i)

def thread_2(i):
    time.sleep(5)
    print('Value by Thread 2:', i)
    
# Creating three sample threads 
thread1 = threading.Thread(target=thread_1, args=(1,))
thread2 = threading.Thread(target=thread_2, args=(2,))

# Running three thread object
thread1.start()
thread1.join(timeout=5)
thread2.start()
thread2.join()

输出

Value by Thread 1:1
Value by Thread 2:2


相关用法


注:本文由纯净天空筛选整理自 Python Thread Class | join() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。