Python 多線程與隊列運用實例

多線程與隊列運用實例

#!/usr/bin/env python
#-*- coding: utf-8 -*-
#

import threading
import queue as Queue


class RunThread(threading.Thread):
    def __init__(self,name,q):
        threading.Thread.__init__(self)
        self.name = name
        self.q = q

    def run(self):
        while True:
            try:
                RunFunction(self.name,self.q).work()
            except:
                break

class RunFunction():
    def __init__(self,threadname,q):
        self.threadname = threadname
        self.q = q

    def work(self):
        q_data = self.q.get(timeout=0.1)
        print('{} get data is : {} \n'.format(self.threadname,q_data))


class Main():
    
    def __init__(self):
        self.threadlist=['Thread_1','Thread_2','Thread_3']
        self.workqueue = Queue.Queue(100)
        self.threads = []
        
    def runthread(self):
        for tname in self.threadlist:
            thread = RunThread(tname,self.workqueue)
            thread.start()
            self.threads.append(thread)
        for tmp in range(10000):
            print('MainThread put the data : {} \n'.format(tmp))
            self.workqueue.put(tmp)
        for t in self.threads:
            t.join()
        print('over........')


if __name__ == '__main__':
    test = Main()
    test.runthread()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章