国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 怀仁县| 阳江市| 彭山县| 苍溪县| 四平市| 娄烦县| 武鸣县| 罗田县| 潼南县| 商城县| 泸水县| 忻州市| 淮滨县| 抚松县| 启东市| 登封市| 安阳县| 淳化县| 镇远县| 赣州市| 密云县| 始兴县| 新乡县| 平陆县| 芮城县| 绵阳市| 馆陶县| 黄陵县| 白水县| 沽源县| 周口市| 巴彦淖尔市| 北碚区| 北流市| 凤山市| 湟中县| 无棣县| 荃湾区| 孟州市| 叙永县| 泽州县|