python 多線程中子線程和主線程相互通信


主線程開啟多個線程去干活,每個線程需要完成的時間不同,干完活以后都要通知給主線程,下面代碼說明該應用:

代碼塊:

import threading
import queue
import time
import random

'''
需求:主線程開啟了多個線程去干活,每個線程需要完成的時間
不同,但是在干完活以后都要通知給主線程
多線程和queue配合使用,實現子線程和主線程相互通信的例子
'''
q = queue.Queue()
threads=[]
class MyThread(threading.Thread):
    def __init__(self,q,t,j):
        super(MyThread,self).__init__()
        self.q=q
        self.t=t
        self.j=j

    def run(self):
        time.sleep(self.j)
        # 通過q.put()方法,將每個子線程要返回給主線程的消息,存到隊列中
        self.q.put("我是第%d個線程,我睡眠了%d秒,當前時間是%s" % (self.t, self.j,time.ctime()))



'''
# 生成15個子線程,加入到線程組里,
    # 每個線程隨機睡眠1-8秒(模擬每個線程干活時間的長短不同)
'''

for i in range(15):
   j=random.randint(1,8)
   threads.append(MyThread(q,i,j))

#    循環開啟所有子線程
for mt in threads:
    mt.start()
print('進程開啟時間:%s'%(time.ctime()))
'''
通過一個while循環,當q隊列中不為空時,通過q.get()方法,
循環讀取隊列q中的消息,每次計數器加一,當計數器到15時,
證明所有子線程的消息都已經拿到了,此時循環停止
'''
count = 0
while True:
    if not q.empty():
        print(q.get())
        count+=1
    if count==15:
        break

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM