Python多線程編程簡單介紹
創(chuàng)建線程
格式如下
threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
這個構(gòu)造器必須用關(guān)鍵字傳參調(diào)用
- group 線程組
- target 執(zhí)行方法
- name 線程名字
- args target執(zhí)行的元組參數(shù)
- kwargs target執(zhí)行的字典參數(shù)
Thread對象函數(shù)
函數(shù) 描述
start() 開始線程的執(zhí)行
run() 定義線程的功能的函數(shù)(一般會被子類重寫)
join(timeout=None) 程序掛起,直到線程結(jié)束;如果給了 timeout,則最多阻塞 timeout 秒
getName() 返回線程的名字
setName(name) 設(shè)置線程的名字
isAlive() 布爾標志,表示這個線程是否還在運行中
isDaemon() 返回線程的 daemon 標志
setDaemon(daemonic) 把線程的 daemon 標志設(shè)為 daemonic(一定要在調(diào)用 start()函數(shù)前調(diào)用)
常用示例
格式
import threading
def run(*arg, **karg):
pass
thread = threading.Thread(target = run, name = "default", args = (), kwargs = {})
thread.start()
實例
#!/usr/bin/python
#coding=utf-8
import threading
from time import ctime,sleep
def sing(*arg):
print "sing start: ", arg
sleep(1)
print "sing stop"
def dance(*arg):
print "dance start: ", arg
sleep(1)
print "dance stop"
threads = []
#創(chuàng)建線程對象
t1 = threading.Thread(target = sing, name = 'singThread', args = ('raise me up',))
threads.append(t1)
t2 = threading.Thread(target = dance, name = 'danceThread', args = ('Rup',))
threads.append(t2)
#開始線程
t1.start()
t2.start()
#等待線程結(jié)束
for t in threads:
t.join()
print "game over"
輸出
sing start: ('raise me up',)
dance start: ('Rup',)
sing stop
dance stop
game over
相關(guān)文章
Python Django中間件,中間件函數(shù),全局異常處理操作示例
這篇文章主要介紹了Python Django中間件,中間件函數(shù),全局異常處理操作,結(jié)合實例形式分析了Django中間件,中間件函數(shù),全局異常處理相關(guān)操作技巧,需要的朋友可以參考下2019-11-11Pandas中的loc與iloc區(qū)別與用法小結(jié)
loc函數(shù):通過行索引 “Index” 中的具體值來取行數(shù)據(jù)(如取"Index"為"A"的行)而iloc函數(shù):通過行號來取行數(shù)據(jù)(如取第二行的數(shù)據(jù)),這篇文章介紹Pandas中的loc與iloc區(qū)別與用法,感興趣的朋友一起看看吧2024-01-01淺談Python中進程的創(chuàng)建與結(jié)束
這篇文章主要介紹了淺談Python中進程的創(chuàng)建與結(jié)束,但凡是硬件,都需要有操作系統(tǒng)去管理,只要有操作系統(tǒng),就有進程的概念,就需要有創(chuàng)建進程的方式,需要的朋友可以參考下2023-07-07python中根據(jù)字符串調(diào)用函數(shù)的實現(xiàn)方法
下面小編就為大家?guī)硪黄猵ython中根據(jù)字符串調(diào)用函數(shù)的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考,一起跟隨小編過來看看吧2016-06-06