1'''2
建立執行緒,也可以動態確定執行緒數
3'''4#
encoding: utf-856
7import
threading
8import
time
9import
random
1011
12def
print_time(thread_name, step):13#
python的time.ctime()函式把乙個時間戳(按秒計算的浮點數)轉化為time.asctime()的形式。14#
如果引數未給或者為none的時候,將會預設time.time()為引數。它的作用相當於asctime(localtime(secs))。
15print(thread_name, ':'
, time.ctime(time.time()))
16time.sleep(step)
1718
19class
mythread(threading.thread):20#
子類的建構函式必須先呼叫其父類的建構函式,重寫run()方法。
21def
__init__(self, thid=none, thname=none, step=0.1):
22 threading.thread.__init__
(self)
23 self.step =step
24 self.thid =thid
25 self.thname =thname
2627
defrun(self):
28for i in range(3):
29print_time(self.thname, self.step)
30time.sleep(self.step)
31print('
%s結束
' %self.thname)
3233
print('
主線程開始!')
3435
36 threads =
37for i in range(10):38#
建立出來的執行緒後面還需要使用,所以使用變數th儲存起來,儲存到迴圈之前事先建立好的列表裡
39 th = mythread(thname='
執行緒%d
' % i, step=round(random.uniform(0, 1), 2))
4041
th.start()
4243
for th in
threads:
44th.join()
4546
print('
主線程結束!
')
Python多執行緒之event
事件 event 用於執行緒間同步和通訊。比如執行緒a要完成某一任務 event 執行緒b才能執行後面的 怎麼實現呢,就是用event。event常用方法 釋義set 開始乙個事件 wait 如果未設定set狀態會一直等待,否則過 clear 清除set狀態 isset 是否設定set狀態 注意 w...
Python多執行緒之threading
1.多執行緒的基礎函式及增加執行緒add thread import threading 1.基礎函式 def main print threading.active count 列印目前程序的數目 print threading.enumerate 檢視程序列表 print threading.c...
python多執行緒之 thread
多執行緒類似於同時執行多個不同程式,多執行緒執行有如下優點 執行緒在執行過程中與程序還是有區別的。每個獨立的執行緒有乙個程式執行的入口 順序執行序列和程式的出口。但是執行緒不能夠獨立執行,必須依存在應用程式中,由應用程式提供多個執行緒執行控制。每個執行緒都有他自己的一組cpu暫存器,稱為執行緒的上下...