开启多线程, 继承Thread类

2018-08-06  本文已影响0人  裴general

import queue
import threading
import time

Thread_id = 1
Thread_num = 5

def running(string):
    print('gogogogogogo' + string)
    time.sleep(2)

class myThread(threading.Thread):
    def __init__(self, q):
        global Thread_id
        threading.Thread.__init__(self)
        self.q = q
        self.Thread_id = Thread_id
        Thread_id = Thread_id + 1

    def run(self):
        while True:
            try:
                task = self.q.get(block=True, timeout=1) #不设置阻塞的话会一直去尝试获取资源
            except queue.Empty:
                print('Thread',  self.Thread_id, 'end')
                break
            #取到数据,开始处理(依据需求加处理代码)
            print("Starting ", self.Thread_id)
            running(task)
            print(task)
            self.q.task_done()
            print("Ending", self.Thread_id)


def main():
    q = queue.Queue(10)

    #向资源池里面放10个数用作测试
    for i in range(10):
        q.put('abc' + str(i))

    #开Thread_num个线程
    start_time = time.time()
    for _ in range(0, Thread_num):
        worker = myThread(q)
        worker.start()
    q.join() #等待所有的队列资源都用完
    end_time = time.time()
    print('共花费时间 %s' % (start_time - end_time))
    print("Exiting Main Thread")

if __name__ == '__main__':
    main()
上一篇下一篇

猜你喜欢

热点阅读