内容字号:默认大号超大号

段落设置:段首缩进取消段首缩进

字体设置:切换到微软雅黑切换到宋体

Python 多线程

2018-04-16 16:36 出处:清屏网 人气: 评论(0

import queue
import threading
import time

class WorkManager:
    def __init__(self):
        self.done_work = []
        self.target_work = queue.Queue()
    def isEmpty(self):
        return self.target_work.empty()
    def getNewWork(self):
        return self.target_work.get()
    def addNewWork(self, newWork):
        if newWork in self.done_work:
            pass
        else:
            self.done_work.append(newWork)
            self.target_work.put(newWork)
    def addDoneWork(self, doneWork):
        self.done_work.append(doneWork)

class DoWork(threading.Thread):
    def __init__(self, workManager, name):
        threading.Thread.__init__(self)
        self.workManager = workManager
        self.name = name
    def run(self):
        while not self.workManager.isEmpty():
            target = self.workManager.getNewWork()
            print('%s do the work:%d' % (self.name, target))
            time.sleep(1)



if __name__ == '__main__':
    need_to_do_array = [1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 9, 10]
    workManager = WorkManager();
    for i in range(len(need_to_do_array)):
        workManager.addNewWork(need_to_do_array[i])

    start_time = time.time()

    all_thread_work = []
    for i in range(5):
        t = DoWork(workManager, "name_%d" % i)
        all_thread_work.append(t)
    for i in range(len(all_thread_work)):
        all_thread_work[i].start()
    for i in range(len(all_thread_work)):
        all_thread_work[i].join()

    end_time = time.time()
    used_time = end_time - start_time
    print(used_time)

1.总结下,就是要继承Thread,然后run一下就可以。 可以看到5个线程,本来要10秒的工作,2秒就做完了。

3332

分享给小伙伴们:
本文标签: Python多线程

相关文章

发表评论愿您的每句评论,都能给大家的生活添色彩,带来共鸣,带来思索,带来快乐。

CopyRight © 2015-2016 QingPingShan.com , All Rights Reserved.

清屏网 版权所有 豫ICP备15026204号