# -*- 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()

相关文章:

  • 2022-01-13
  • 2021-11-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-17
猜你喜欢
  • 2021-10-18
  • 2022-12-23
  • 2022-01-07
  • 2022-12-23
  • 2022-12-23
  • 2021-07-19
  • 2021-07-10
相关资源
相似解决方案