码迷,mamicode.com
首页 > 编程语言 > 详细

python threading 模块来实现多线程

时间:2015-12-26 14:59:52      阅读:169      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!