首页 > 编程语言 > 详细

python threading 模块来实现多线程

时间:2015-12-26 14:57:31      阅读:206      评论:0      收藏:0      [点我收藏+]

以多线程的方式向标准输出打印日志 

 

#!/usr/bin/python

import time
import threading

class PrintThread(threading.Thread):
    def __init__(self,threadid,count,mutex):
        threading.Thread.__init__(self)
        self.threadid=threadid
        self.count=count
        self.mutex=mutex
    def run(self):
        with self.mutex:
            for item in range(self.count):
                time.sleep(0.05)
                print threadid is {0} this is the count {1}.format(self.threadid,item)

class PrintThread2(threading.Thread):
    def __init__(self,threadid,count,mutex):
        threading.Thread.__init__(self)
        self.threadid=threadid
        self.count=count
        self.mutex=mutex
    def run(self):
        for item in range(self.count):
            with self.mutex:
                time.sleep(0.1)
                print thread id is {0} this is the count {1}.format(self.threadid,item)

if __name__=="__main__":
    threads=[]
    stdoutLock=threading.Lock()
    for item in range(5):
        pt=PrintThread2(item,100,stdoutLock)
        threads.append(pt)
        pt.start()
    for item in threads:
        item.join()
    print this end ...
    

 

python threading 模块来实现多线程

原文:http://www.cnblogs.com/JiangLe/p/5078054.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!