python线程

import threading import time import random #生产者 class Producer(threading.Thread): def __init__(self, threadName, shareObject): threading.Thread.__init__(self, name = threadName) self.shareObject = shareObject def run(self): cnt = 0 while True: time.sleep(1) x = random.randrange(1, 1000) self.shareObject.set(x) print(('%s threading product %d/n') % (threading.currentThread().getName(), x)) cnt += 1 if cnt >= 1000: break; #消费者 class Customer(threading.Thread): def __init__(self, threadName, shareObject): threading.Thread.__init__(self, name = threadName) self.shareObject = shareObject def run(self): cnt = 0 while True: time.sleep(4) x = self.shareObject.get() print(('%s threading consum %d/n') % (threading.currentThread().getName(), x)) cnt += 1 if cnt >= 1000: break; #共享区 class ShareInt: def __init__(self): self.threadCondition = threading.Condition() self.shareObject = [] def set(self, num): self.threadCondition.acquire() if len(self.shareObject) >= 100: print(('%s threading try product! But shareObject is full/n') % (threading.currentThread().getName())) self.threadCondition.wait() self.shareObject.append(num) self.threadCondition.notify() self.threadCondition.release() def get(self): self.threadCondition.acquire() if len(self.shareObject) == 0: print(('%s threading try consum! But shareObject is empty/n') % (threading.currentThread().getName())) self.threadCondition.wait() x = self.shareObject[0] self.shareObject.remove(x) self.threadCondition.notify() self.threadCondition.release() return x #测试 if __name__ == '__main__': shareObject1 = ShareInt() producer1 = Producer('liyong', shareObject1) customer1 = Customer('cc', shareObject1) producer1.start() customer1.start() producer1.join() customer1.join() print('main threading over!/n') else: print('I am being imported from another module/n')

你可能感兴趣的:(python,测试,Class,import)