queue 可以保证每个线程取和存数据的安全性,因为它里面实现了锁机制
#-*-coding:utf-8-*-
#__author:martin
#date:2017/10/23
import threading
import random
import time
class Producer(threading.Thread):
def run(self):
global L
while True:
val = random.randint(0,100)
print('生产者',self.name,'append '+str(val),L)
if lock_con.acquire():
L.append(val)
lock_con.notify()
lock_con.release()
time.sleep(3)
class Consumer(threading.Thread):
def run(self):
global L
while True:
if lock_con.acquire():
if len(L) == 0 :
lock_con.wait()
print('消费者', self.name, 'delete ' + str(L[0]), L)
del L[0]
lock_con.release()
time.sleep(1)
if __name__ == '__main__':
L = []
lock_con = threading.Condition()
threads = []
for i in range(5):
threads.append(Producer())
threads.append(Consumer())
for t in threads:
t.start()
for j in threads:
j.join()
print('======================')