<strike id="gcwsi"></strike>
  • <ul id="gcwsi"></ul>

    千鋒教育-做有情懷、有良心、有品質(zhì)的職業(yè)教育機(jī)構(gòu)

    400-811-9990
    手機(jī)站
    千鋒教育

    千鋒學(xué)習(xí)站 | 隨時(shí)隨地免費(fèi)學(xué)

    千鋒教育

    掃一掃進(jìn)入千鋒手機(jī)站

    領(lǐng)取全套視頻
    千鋒教育

    關(guān)注千鋒學(xué)習(xí)站小程序
    隨時(shí)隨地免費(fèi)學(xué)習(xí)課程

    上海
    • 北京
    • 鄭州
    • 武漢
    • 成都
    • 西安
    • 沈陽(yáng)
    • 廣州
    • 南京
    • 深圳
    • 大連
    • 青島
    • 杭州
    • 重慶
    當(dāng)前位置:哈爾濱千鋒IT培訓(xùn)  >  技術(shù)干貨  >  python線程編寫的兩種方法

    python線程編寫的兩種方法

    來(lái)源:千鋒教育
    發(fā)布人:xqq
    時(shí)間:2023-11-09 15:19:02

    Python中如果要使用線程的話,python的lib中提供了兩種方式。一種是函數(shù)式,一種是用類來(lái)包裝的線程對(duì)象。舉兩個(gè)簡(jiǎn)單的例子希望起到拋磚引玉的作用,關(guān)于多線程編程的其他知識(shí)例如互斥、信號(hào)量、臨界區(qū)等請(qǐng)參考python的文檔及相關(guān)資料。

    1、調(diào)用thread模塊中的start_new_thread()函數(shù)來(lái)產(chǎn)生新的線程,請(qǐng)看代碼:

    python代碼

    ###thread_example.py

    importtime

    importthread

    deftimer(no,interval):#自己寫的線程函數(shù)

    whileTrue:

    print'Thread:(%d)Time:%s'%(no,time.ctime())

    time.sleep(interval)

    deftest():#使用thread.start_new_thread()來(lái)產(chǎn)生2個(gè)新的線程

    thread.start_new_thread(timer,(1,1))

    thread.start_new_thread(timer,(2,3))

    if__name__=='__main__':

    test()

    這個(gè)是thread.start_new_thread(function,args[,kwargs])函數(shù)原型,其中function參數(shù)是你將要調(diào)用的線程函數(shù);args是講傳遞給你的線程函數(shù)的參數(shù),他必須是個(gè)tuple類型;而kwargs是可選的參數(shù)。

    線程的結(jié)束一般依靠線程函數(shù)的自然結(jié)束;也可以在線程函數(shù)中調(diào)用thread.exit(),他拋出SystemExitexception,達(dá)到退出線程的目的。

    2、通過(guò)調(diào)用threading模塊繼承threading.Thread類來(lái)包裝一個(gè)線程對(duì)象。請(qǐng)看代碼:

    python代碼

    importthreading

    importtime

    classtimer(threading.Thread):#我的timer類繼承自threading.Thread類

    def__init__(self,no,interval):

    #在我重寫__init__方法的時(shí)候要記得調(diào)用基類的__init__方法

    threading.Thread.__init__(self)

    self.no=no

    self.interval=interval

    defrun(self):#重寫run()方法,把自己的線程函數(shù)的代碼放到這里

    whileTrue:

    print'ThreadObject(%d),Time:%s'%(self.no,time.ctime())

    time.sleep(self.interval)

    deftest():

    threadone=timer(1,1)#產(chǎn)生2個(gè)線程對(duì)象

    threadtwo=timer(2,3)

    threadone.start()#通過(guò)調(diào)用線程對(duì)象的.start()方法來(lái)激活線程

    threadtwo.start()

    if__name__=='__main__':

    test()

    其實(shí)thread和threading的模塊中還包含了其他的很多關(guān)于多線程編程的東西,例如鎖、定時(shí)器、獲得激活線程列表等等。

    以上內(nèi)容為大家介紹了python中的反斜杠,希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。http://www.mobiletrain.org/

    聲明:本站稿件版權(quán)均屬千鋒教育所有,未經(jīng)許可不得擅自轉(zhuǎn)載。

    猜你喜歡LIKE

    python函數(shù)中的參數(shù)有哪些?

    2023-11-14

    python中pygal模塊如何使用?

    2023-11-14

    Python描述符中有哪三種方法?

    2023-11-14

    最新文章NEW

    如何使用python any()判斷多元素?

    2023-11-14

    python中doctest庫(kù)是什么?

    2023-11-14

    python模塊引入的三種方式

    2023-11-14

    相關(guān)推薦HOT

    更多>>

    快速通道 更多>>

    最新開(kāi)班信息 更多>>

    網(wǎng)友熱搜 更多>>