1. 程式人生 > >python_day29_通過類建立多執行緒_佇列

python_day29_通過類建立多執行緒_佇列

#Author:'haijing'
#date:2018/12/20
import threading
import time
#通過類建立多執行緒


class MyThread(threading.Thread): #MyThread類繼承threading.Thread類
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num

def run(self): # run是threading.Thread中的方法

print("running on number:%s" % self.num)


time.sleep(3)


if __name__ == '__main__': #這一句可以報程在本py檔案中可以執行,在別的py檔案中呼叫這個頻域檔案時候(即import ...不會去執行t1.start等)
t1 = MyThread(1) #建立執行緒物件t1,執行這一句的時候,self.num=1這個變數存在了一塊記憶體中
t2 = MyThread(2) #建立執行緒物件t2,執行這一句的時候,self.num=1這個變數存在了另一塊記憶體中,和上面的互不干擾
t1.start() #執行執行緒t1 實際執行的是run方法
t2.start() #執行執行緒t1


佇列
#Author:'haijing'

#date:2018/12/20
# import queue
#
# d = queue.Queue() #建立一個佇列 是用來放資料的,預設引數為0表示可以儲存引數的大小為無窮大
# d.put('jinxing') #將'jingxing'插入佇列d中
# d.put('xiaohu') #將xiaohu插入佇列中,並防止jinxing的後面
# d.put('123')
# #預設是先進先出
# print(d.get()) #jinxing
# print(d.get()) #xiaohu
# print(d.get()) #123
# # print(d.get()) #一旦全部拿出來後,再去佇列中拿資料,程式會阻塞住,因為程式一直在等待著另外的資料補充進來

#
# d1 = queue.Queue(4) #表示可以往d1中插入4個數據
#但是一旦插入5個數據,如果d.put('haijing')程式就會阻塞住,除非有一個數據出去了
#一旦插入5個數據,如果d.put('haijing',1)程式就會報錯

#佇列可以解決多執行緒的問題
#如果是列表,很多個執行緒都可以去拿最後一個數,導致不安全
#進一步想,如果列表中的每個數都是一個任務的話,多個執行緒去拿同一個任務的話就不好了
#所以用佇列,一個執行緒get一下,下一個執行緒再去get肯定是拿到的下一個數
import threading,queue
from time import sleep
from random import randint
class Production(threading.Thread): #“生產執行緒”的類
def run(self): #具體生產的方法
while True:
r=randint(0,100) #產生一個0-100之間的數
q.put(r) #將隨機產生的數字放入佇列q中去
print("生產出來%s號包子"%r)
sleep(1) #必須有這一句,以阻塞住“生產執行緒”的執行,要不然就是“生產執行緒”一直在執行了,沒有“吃的執行緒去執行了”
class Proces(threading.Thread): #“吃的執行緒”的類
def run(self):
while True:
re=q.get() #按照放進q中的順序一個一個的拿出來,並賦值給re
print("吃掉%s號包子"%re)
if __name__=="__main__":
q=queue.Queue(10) #產生一個數據大小為10的佇列q
threads=[Production(),Production(),Production(),Proces()]
for t in threads: #類似於t1=Production()->“生產執行緒”物件 t2=Production()—>"生產執行緒"物件 t3=Production() t4=Proces()->“吃執行緒”物件
t.start() #t1.start->"生產執行緒"執行 t2.start t2.start t2.start->“吃執行緒”執行

#即建立了4個執行緒,cpu每次也都是執行一個執行緒,只不過當某個執行緒阻塞住(例如有延時),會去執行另外一個執行緒,這樣來提高效率

2018.12.20 haijing in HZ
晚 馬上回宿舍了