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

首頁 > 編程 > Python > 正文

Python 多線程的實例詳解

2020-02-16 10:10:48
字體:
來源:轉載
供稿:網友

 Python 多線程的實例詳解

一)線程基礎

1、創(chuàng)建線程:

thread模塊提供了start_new_thread函數,用以創(chuàng)建線程。start_new_thread函數成功創(chuàng)建后還可以對其進行操作。
其函數原型:

  start_new_thread(function,atgs[,kwargs])

其參數含義如下:

    function: 在線程中執(zhí)行的函數名
    args:元組形式的參數列表。
    kwargs: 可選參數,以字典的形式指定參數

方法一:通過使用thread模塊中的函數創(chuàng)建新線程。

>>> import thread >>> def run(n):   for i in range(n):     print i       >>> thread.start_new_thread(run,(4,))  #注意第二個參數一定要是元組的形式 53840   1 >>>  2 3 KeyboardInterrupt >>> thread.start_new_thread(run,(2,)) 17840   1 >>>  thread.start_new_thread(run,(),{'n':4}) 39720   1 >>>  2 3 thread.start_new_thread(run,(),{'n':3}) 32480   1 >>>  2 

方法二:通過繼承threading.Thread創(chuàng)建線程

>>> import threading >>> class mythread(threading.Thread):   def __init__(self,num):     threading.Thread.__init__(self)     self.num = num   def run(self):        #重載run方法     print 'I am', self.num       >>> t1 = mythread(1) >>> t2 = mythread(2) >>> t3 = mythread(3) >>> t1.start()      #運行線程t1 I am >>> 1 t2.start() I am >>> 2 t3.start() I am >>> 3 

方法三:使用threading.Thread直接在線程中運行函數。

import threading >>> def run(x,y):   for i in range(x,y):     print i  >>> t1 = threading.Thread(target=run,args=(15,20)) #直接使用Thread附加函數args為函數參數  >>> t1.start() 15 >>>  16 17 18 19 

二)Thread對象中的常用方法:

1、isAlive方法:

>>> import threading >>> import time >>> class mythread(threading.Thread):   def __init__(self,id):     threading.Thread.__init__(self)     self.id = id   def run(self):     time.sleep(5)  #休眠5秒     print self.id       >>> t = mythread(1) >>> def func():   t.start()   print t.isAlive()  #打印線程狀態(tài)     >>> func() True >>> 1 

2、join方法:

原型:join([timeout]) 

    timeout: 可選參數,線程運行的最長時間

import threading >>> import time   #導入time模塊 >>> class Mythread(threading.Thread):   def __init__(self,id):     threading.Thread.__init__(self)     self.id = id   def run(self):     x = 0     time.sleep(20)     print self.id       >>> def func():   t.start()   for i in range(5):     print i       >>> t = Mythread(2) >>> func() 0 1 2 3 4 >>> 2 def func():   t.start()   t.join()   for i in range(5):     print i       >>> t = Mythread(3) >>> func() 3 0 1 2 3 4 >>>              
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 广元市| 永宁县| 城口县| 库尔勒市| 靖西县| 清涧县| 黄平县| 泰州市| 西城区| 清新县| 正宁县| 泾阳县| 腾冲县| 桂阳县| 许昌市| 珲春市| 巢湖市| 梅河口市| 西畴县| 吉林省| 青河县| 通山县| 青龙| 安福县| 新乐市| 龙川县| 贞丰县| 塘沽区| 甘肃省| 新晃| 汉寿县| 师宗县| 台中县| 临漳县| 云南省| 南投市| 南投市| 安宁市| 廉江市| 宾川县| 合江县|