位於 time 模塊中的 sleep(secs) 函數,可以實現令當前執行的線程暫停 secs 秒後再繼續執行。所謂暫停,即令當前線程進入阻塞狀態,當達到 sleep() 函數規定的時間後,再由阻塞狀態轉為就緒狀態,等待 CPU 調度。
sleep() 函數位於 time 模塊中,因此在使用前,需先引入 time 模塊。
sleep() 函數的語法規則如下所示:
time.sleep(secs)
其中,secs 參數用於指定暫停的秒數,
仍以前面章節創建的 thread 線程為例,下面程序演示了 sleep() 函數的用法:
import threadingimport timedef action(*add): for arc in add: time.sleep(0.1) print(threading.current_thread().getName() +" "+ arc)my_tuple = ("http://c.biancheng.net/python/",\ "http://c.biancheng.net/shell/",\ "http://c.biancheng.net/java/")thread = threading.Thread(target = action,args =my_tuple)thread.start()for i in range(5): print(threading.current_thread().getName())程序執行結果為:
MainThread
MainThread
MainThread
MainThread
MainThread
Thread-1 http://c.biancheng.net/python/
Thread-1 http://c.biancheng.net/shell/
Thread-1 http://c.biancheng.net/java/可以看到,和未使用 sleep() 函數的輸出結果相比,顯然主線程 MainThread 在前期獲得 CPU 資源的次數更多,因為 Thread-1 線程中調用了 sleep() 函數,在一定程序上會阻礙該線程獲得 CPU 調度。