Python スレッドの join メソッドを使用する方法

Python では、join()メソッドはスレッドがそのタスクを完了するまで待機するために使われます。スレッドがjoin()メソッドを呼び出すと、メインスレッドはそのスレッドの実行が終わるまで待ってから、その後のコードの実行を続けます。

join() メソッドには 2 つの使用法があります。

  1. 結合する
import threading

def my_function():
    print("Thread started")
    # 执行线程任务
    print("Thread finished")

# 创建线程
my_thread = threading.Thread(target=my_function)

# 启动线程
my_thread.start()

# 等待线程执行完成
my_thread.join()

print("Main thread finished")

あなたの最適な友人が誰なのかは明らかです

Thread started
Thread finished
Main thread finished
  1. join(timeout)
import threading

def my_function():
    print("Thread started")
    # 模拟长时间运行的任务
    for _ in range(5):
        pass
    print("Thread finished")

# 创建线程
my_thread = threading.Thread(target=my_function)

# 启动线程
my_thread.start()

# 等待线程执行完成,最多等待1秒
my_thread.join(1)

print("Main thread finished")

ネイティブな日本語で文章を言い換えると、次のようになります。

Thread started
Thread finished
Main thread finished

主スレッドがjoin()メソッド呼び出し前にスレッドが完了していた場合は、join()メソッドは何も待たずにただちにリターンすることに注意してください。

bannerAds