python 生产消费案例1

#!/usr/bin/env python #-*- coding:utf-8 -*- import threading,random,time VALUE = https://www.it610.com/article/1000 Lock = threading.Lock()class Product(threading.Thread): def run(self): global VALUE while True: m = random.randint(100,500) Lock.acquire() VALUE += m print('%s 生成了数字 %s ,现在数字大小为 %s ' %(threading.current_thread(),m,VALUE)) Lock.release() time.sleep(0.5)class Consumer(threading.Thread): def run(self): global VALUE while True: m = random.randint(200,600) Lock.acquire() if VALUE >= m: VALUE -= m print('%s 消费了数字 %s ,现在数字大小为 %s ' %(threading.current_thread(),m,VALUE)) else: print('数字 %s 太小' %VALUE) Lock.release() time.sleep(0.5)def main(): for x in range(3): t = Consumer(name='消费者线程%d' %(x)) t.start()for x in range(5): t = Product(name='生产者线程%d' %(x)) t.start()if __name__ == '__main__': main()

    推荐阅读