當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。