国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python threading多線程編程實例

2020-02-23 05:49:34
字體:
來源:轉載
供稿:網友

Python 的多線程有兩種實現方法:

函數,線程類

1.函數

調用 thread 模塊中的 start_new_thread() 函數來創建線程,以線程函數的形式告訴線程該做什么

代碼如下:
# -*- coding: utf-8 -*-
import thread
def f(name):
  #定義線程函數
  print "this is " + name
 
if __name__ == '__main__':
  thread.start_new_thread(f, ("thread1",))
  #用start_new_thread()調用線程函數和其他參數
  while 1:
    pass

不過這種方法暫時沒能找到其他輔助方法,連主線程等待都要用 while 1 這種方法解決。

2.線程類

調用 threading 模塊,創建 threading.Thread 的子類來得到自定義線程類。
代碼如下:
# -*- coding: utf-8 -*-
import threading
class Th(threading.Thread):
  def __init__(self, name):
    threading.Thread.__init__(self)
    self.t_name = name
    #調用父類構造函數
 
  def run(self):
    #重寫run()函數,線程默認從此函數開始執行
    print "This is " + self.t_name
 
if __name__ == '__main__':
  thread1 = Th("Thread_1")
  thread1.start()
  #start()函數啟動線程,自動執行run()函數

threading.Thread 類的可繼承函數:
getName() 獲得線程對象名稱
setName() 設置線程對象名稱
join() 等待調用的線程結束后再運行之后的命令
setDaemon(bool) 阻塞模式, True: 父線程不等待子線程結束, False 等待,默認為 False
isDaemon() 判斷子線程是否和父線程一起結束,即 setDaemon() 設置的值
isAlive() 判斷線程是否在運行

實例

代碼如下:
import threading
import time
class Th(threading.Thread):
  def __init__(self, thread_name):
    threading.Thread.__init__(self)
    self.setName(thread_name)
 
  def run(self):
    print "This is thread " + self.getName()
    for i in range(5):
      time.sleep(1)
      print str(i)
    print self.getName() + "is over"

join() 阻塞等待

代碼如下:
if __name__ == '__main__':
    thread1 = Th("T1 ")
    thread1.start()
    #thread1.join()
    print "main thread is over"

不帶 thread1.join() ,得到如下結果:
代碼如下:
This is thread T1
main thread is over
0
1
2
T1 is over

不等待 thread1 完成,執行之后語句。
加了 thread1.join() ,得到如下結果:

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南城县| 彭阳县| 长兴县| 合水县| 申扎县| 五指山市| 景洪市| 福泉市| 太原市| 清苑县| 门源| 沈丘县| 磐石市| 贵定县| 翁牛特旗| 河北区| 昂仁县| 玛纳斯县| 沾化县| 榆社县| 宁安市| 阳信县| 龙陵县| 道真| 涿鹿县| 呼图壁县| 略阳县| 林州市| 赫章县| 西和县| 大渡口区| 德化县| 巴林左旗| 布拖县| 京山县| 万山特区| 奎屯市| 夏津县| 卫辉市| 抚远县| 四平市|