多線程模塊:threading
阿新 • • 發佈:2019-02-07
創建 utf-8 三次 並發 多個 時間 .py fun 執行函數
threading 常見用法:
(1) 在 thread 中,我們是通過 thread.start_new_thread(function, args) 來開啟一個線程,接收一個函數和該函數的參數,函數的參數必須是元組的形式
(2) 在 threading 中,我們是通過 threading.Thread(target=function, args=(....)) 來創建一個對象,然後再通過對象的 start() 方法來開啟一個線程,多個線程可以並發執行
#!/usr/bin/env python #-*- coding:utf-8 -*- import time import threadingdef fun(): print time.ctime() time.sleep(1) for i in range(3): t = threading.Thread(target=fun, args=()) # 創建一個 Thread 對象,接收一個函數和該函數的參數 t.start() # 通過對象來開啟一個新的線程,通過線程來執行函數
[root@localhost ~]$ python 1.py # 多個線程並發執行,只需要執行一秒 Mon Jan28 21:15:35 2019 Mon Jan 28 21:15:35 2019 Mon Jan 28 21:15:35 2019
t.join()方法用於阻塞下一個線程的運行,等待當前線程執行完再執行下一個線程,例子如下:
#!/usr/bin/env python #-*- coding:utf-8 -*- import time import threading def fun(): print time.ctime() time.sleep(1) for i in range(3): t = threading.Thread(target=fun, args=()) t.start() t.join()
[root@localhost ~]$ python 1.py # 由於線程被阻塞,需要執行3秒 Mon Jan 28 21:33:35 2019 Mon Jan 28 21:33:36 2019 Mon Jan 28 21:33:37 2019
t.setDaemon()方法用於是否設置當前線程隨著主線程的退出而退出,例子如下:
#!/usr/bin/env python #-*- coding:utf-8 -*- import time import threading def fun(): # 函數的功能是打印三次當前時間 for i in range(3):
print time.ctime() time.sleep(1) t = threading.Thread(target=fun, args=()) t.setDaemon(True) t.start()
print ‘End...‘ # 執行 print 之後,主線程就退出了,最終結果只會打印一次
[root@localhost ~]$ python 1.py Mon Jan 28 21:54:48 2019
End...
多線程模塊:threading