Python多线程应用示例

阅读更多
import threading

commonlist=range(20)
commonlist.reverse()

class Mythread(threading.Thread):
    def __init__(self, lock, threadname):
        #super(Mythread, self).__init__(name=threadname)
        threading.Thread.__init__(self)
        self.lock=lock
    
    def run(self):
        #global commonlist
        flag=True
        while(flag):
            self.lock.acquire()
            if(len(commonlist)==0):
                flag=False
            else:
                item=commonlist.pop()
                print "%s get %d"%(self.getName(),item)
            self.lock.release()
    
def main():
    lock=threading.Lock()
    for i in range(5):
        Mythread(lock, "thread-%d"%i).start()
    
if __name__ == '__main__':
    main()

你可能感兴趣的:(py)