---
# System prepended metadata

title: ch30_26.py

---

# ch30_26.py
```
import threading, time, random, queue
s = time.process_time()
q = queue.Queue(10) #建立queue,最多10筆
a = 0.1
b = 5
def producer(): #生產者狀況
    while True:
        if not q.full(): #如果queue有空間
            item = random.randint(1,100) #生產產品
            q.put(item) #將產品放入庫存
            print(f"生產者存入 {item}")
            #time.sleep(a) #休息a秒
        if time.process_time() - s > b: break
            
def consumer(): #消費者狀況
    while True:
        if not q.empty(): #如果queue不是空的
            item = q.get() #取得產品
            print(f"消費者取得 {item} : queue數量 {q.qsize()}")
            #time.sleep(a) #休息a秒
        if time.process_time() - s > b: break

p = threading.Thread(name='producer',target=producer) #建立producer執行緒
c = threading.Thread(name='consumer',target=consumer) #建立consumer執行緒
p.start()
time.sleep(a)
c.start()
time.sleep(a)
```