簡體   English   中英

Python 多線程:time.sleep() 無效

[英]Python Multithreading: time.sleep() is not having effect

我必須在我的 python 多線程代碼中添加一個時間延遲。 我嘗試過使用 time.sleep(),但似乎 time.sleep 沒有任何效果。 我在這里做錯了什么? 有沒有其他方法可以在線程中添加延遲(沒有任何事件驅動邏輯)? 下面是代碼的行為方式與第一個線程應該運行的方式相同,最后,它有 3 秒的延遲,然后第二個線程啟動,最后等待 3 秒。

import threading 
import time
def print_hello():
    print("Hello")
    time.sleep(3)

def print_hi(): 
    print("Hi") 
    time.sleep(3)

t1 = threading.Thread(target=print_hello)  
t2 = threading.Thread(target=print_hi)  

t1.start()
t2.start()

如果要啟動第一個線程,等待 3 秒,然后啟動第二個,只需將 time.sleep() 放在t1.start()t2.start()之間。

如果要啟動第一個線程,請等待它完成(在第一個線程中暫停 3 秒),然后啟動第二個線程,在t1.start()t2.start()之間放置一個t1.join()t2.start() ,等待第一個線程結束后再開始第二個線程。

如果你想讓應用程序考慮等待,你需要讓它等待t1線程結束,然后再啟動t2線程,試試下面的代碼:

import threading 
import time
def print_hello():
    print("Hello")
    time.sleep(3)

def print_hi(): 
    print("Hi") 
    time.sleep(3)

t1 = threading.Thread(target=print_hello)  
t2 = threading.Thread(target=print_hi)  

t1.start()
t1.join()
t2.start()
t2.join()

t1.join()將確保t1線程在啟動t2線程之前完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM