溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python3多線程操作簡(jiǎn)單示例

發(fā)布時(shí)間:2020-09-05 19:46:12 來(lái)源:腳本之家 閱讀:158 作者:愛(ài)代碼也愛(ài)生活 欄目:開(kāi)發(fā)技術(shù)

本文實(shí)例講述了Python3多線程操作。分享給大家供大家參考,具體如下:

python3 線程中常用的兩個(gè)模塊為:

_thread

threading(推薦使用)

thread 模塊已被廢棄。用戶可以使用 threading 模塊代替。所以,在 python3 中不能再使用"thread" 模塊。為了兼容性,python3 將 thread 重命名為 "_thread"。

test.py

# -*- coding:utf-8 -*-
#!/usr/bin/python3
import _thread
import time
# 定義線程調(diào)用函數(shù)
def echo_name(tag,delay):
  count=0
  while count<5:
    time.sleep(delay)
    count+=1
    print("%s:%s" % ( tag,time.ctime(time.time()) ))
#創(chuàng)建2個(gè)線程
try:
  _thread.start_new_thread( echo_name,("thread_1",2))
  _thread.start_new_thread( echo_name,("thread_2",5))
except:
  print("error:無(wú)法啟動(dòng)線程")
#死循環(huán)
while 1:
  pass

執(zhí)行結(jié)果

[root@mail pythonCode]# python3 test.py
thread_1:Wed Jul 20 18:03:39 2016
thread_1:Wed Jul 20 18:03:41 2016
thread_2:Wed Jul 20 18:03:42 2016
thread_1:Wed Jul 20 18:03:43 2016
thread_1:Wed Jul 20 18:03:45 2016
thread_2:Wed Jul 20 18:03:47 2016
thread_1:Wed Jul 20 18:03:47 2016
thread_2:Wed Jul 20 18:03:52 2016
thread_2:Wed Jul 20 18:03:57 2016
thread_2:Wed Jul 20 18:04:02 2016

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python進(jìn)程與線程操作技巧總結(jié)》、《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI