# -*- coding:utf-8 -*-
import threading
from random import Random
import time
class Producer(threading.Thread):
def __init__(self, products, lock):
threading.Thread.__init__(self)
self.__products = products
self.__lock = lock
def run(self):
_random = Random(100)
while True:
if len(self.__products) > 10:
print('Producer 退出')
break
try:
self.__lock.acquire()
n = _random.randint(1, 99)
self.__products.append(n)
print("生产出一个产品:{0}".format(n))
print(self.__products)
finally:
self.__lock.release()
time.sleep(2)
class Comsumer(threading.Thread):
def __init__(self, products, lock):
threading.Thread.__init__(self)
self.__products = products
self.__lock = lock
def run(self):
while True:
if len(self.__products) > 10:
print('Comsumer 退出')
break
try:
self.__lock.acquire()
n = self.__products.pop(0)
print("消费一个产品:{0}".format(n))
print(self.__products)
finally:
self.__lock.release()
time.sleep(3)
def main():
products = [24, 53]
lock = threading.Lock()
p = Producer(products, lock)
c = Comsumer(products, lock)
p.start()
c.start()
if __name__ == '__main__':
main()