import time
import queue
import threading
class ThreadProductorConsumer():
def __init__(self):
self.q = queue.Queue(15)
self.screen_lock = threading.Semaphore(value=1)
def productor(self, product):
while True:
self.q.put(product)
cur_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
cur_name = threading.current_thread().name
self.screen_lock.acquire()
print(cur_time+" " + cur_name + " 生产了一个产品", sep='\n')
self.screen_lock.release()
time.sleep(3)
def consumer(self):
while True:
self.q.get()
cur_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
cur_name = threading.current_thread().name
self.screen_lock.acquire()
print(cur_time + " " + cur_name + " 消费了一个产品", sep='\n')
self.screen_lock.release()
time.sleep(2)
if __name__ == "__main__":
tpc = ThreadProductorConsumer()
p = "product"
for i in range(3):
t = threading.Thread(target=tpc.productor, args=(p,))
t.start()
for j in range(6):
v = threading.Thread(target=tpc.consumer)
v.start()