python多线程老是报错。大神帮忙看看哈? 5
以下是代码:importthreadingimporttimeproducts=[]condition=threading.Condition()classConsume...
以下是代码:
import threading
import time
products=[]
condition = threading.Condition()
class Consumer(threading.Thread):
def consume(self):
global condition
global products
conditon.acquire()
if len(products)==0:
condition.wait()
print('消费提醒:没有产品去消费了')
products.pop()
print('消费者提醒:消费1个产品')
print('消费者提醒:还能消费的产品数为'+str(len(products)))
condition.notify()
condition.release()
def run(self):
for i in range(0,20):
time.sleep(4)
self.consume()
class Producer(threading.Thread):
def produce(self):
global condition
global products
condition.acquire()
if len(products)==10:
condition.wait()
print('生产者提醒:生成的产品数为'+str(len(products)))
print('生产者提醒:停止生产!')
products.append(1)
print('生产者提醒:产品总数为'+str(len(products)))
condition.notify()
condition.release()
def run(self):
for i in range(0,20):
time.sleep(1)
self.produce()
producer=Producer()
consumer=Consumer()
consumer.start()
producer.start()
producer.join()
consumer.join()
报错的提示:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python38-32/对对对.py", line 22, in run
self.consume()
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python38-32/对对对.py", line 10, in consume
conditon.acquire()
NameError: name 'conditon' is not defined 展开
import threading
import time
products=[]
condition = threading.Condition()
class Consumer(threading.Thread):
def consume(self):
global condition
global products
conditon.acquire()
if len(products)==0:
condition.wait()
print('消费提醒:没有产品去消费了')
products.pop()
print('消费者提醒:消费1个产品')
print('消费者提醒:还能消费的产品数为'+str(len(products)))
condition.notify()
condition.release()
def run(self):
for i in range(0,20):
time.sleep(4)
self.consume()
class Producer(threading.Thread):
def produce(self):
global condition
global products
condition.acquire()
if len(products)==10:
condition.wait()
print('生产者提醒:生成的产品数为'+str(len(products)))
print('生产者提醒:停止生产!')
products.append(1)
print('生产者提醒:产品总数为'+str(len(products)))
condition.notify()
condition.release()
def run(self):
for i in range(0,20):
time.sleep(1)
self.produce()
producer=Producer()
consumer=Consumer()
consumer.start()
producer.start()
producer.join()
consumer.join()
报错的提示:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python38-32/对对对.py", line 22, in run
self.consume()
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python38-32/对对对.py", line 10, in consume
conditon.acquire()
NameError: name 'conditon' is not defined 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询