python threading 模块来实现多线程

时间:2023-12-17 08:37:14

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

#!/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 ...'