Pythonでスレッドを作成して速度を制限する方法は?
time.sleep()関数を使用して、スレッドの速度を制限することができます。この関数は、指定した時間の間、スレッドの実行を一時停止することができます。
例えば、次のコードは、1秒ごとにスレッド名をプリントするシンプルなスレッドを作成します。
import threading
import time
def print_thread_name():
while True:
print(threading.currentThread().getName())
time.sleep(1)
# 创建线程
thread = threading.Thread(target=print_thread_name)
# 启动线程
thread.start()
この例では、time.sleep(1)関数により、スレッドはループごとに1秒間停止します。time.sleep()関数のパラメータを調整することで、スレッドの速度を制御することができます。