数据结构与算法(4) 队列
队列
1. 队列的实现
初步设想:列表 + 两个下标指针
创建一个列表和两个变量,front变量指向队首,rear变量指向队尾。初始时,front和rear都为0
进队操作:元素写到li[rear]位置,rear自增1
出队操作:返回li[front]的元素,front自减1
import time,threading
class Queue:
def __init_(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self,item):
self.items.insert(0,item)
def dequeue(self):
if self.items != []:
return self.items.pop()
else:
return False
def size(self):
return len(self.items)
def top(self):
if self.items != []:
return self.items[len(self.items) - 1]
else:
return False
class Counter(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.waitQueue = Queue()
self.lock = threading.Lock()
def calling(self):
while True:
time.sleep(5)
if not self.waitQueue.isEmpty():
self.lock.acquire()
print(f'请客户{self.waitQueue.top()},到{threading.current_thread().name}窗口办理业务')
self.waitQueue.dequeue()
self.lock.release()
class bankSystem:
def __init__(self):
self.serviceQueue = Queue()
self.nowNum = 0
self.maxSize = 100
def getNumber(self):
if self.nowNum < self.maxSize:
self.nowNum +=1
return self.nowNum
else:
print('现在业务繁忙,请稍后再来')
if __name__ == "__main__":
res = bankSystem()
windowcount = 3
serviceWindow = [None] * windowcount
threadList = [None] * windowcount
for i in range(windowcount):
serviceWindow[i] = Counter()
serviceWindow[i].waitQueue = res.serviceQueue
threadList[i] = threading.Thread(name=(i+1),target=serviceWindow[i].calling,args=())
threadList[i].start()
while True:
input('请点击触摸屏获取号码: ')
callNumber = res.getNumber()
if res.serviceQueue != None:
print('您当前的号码为' + str(callNumber) + ", 您前面还有" + str(res.serviceQueue.size())+ "个人")
res.serviceQueue.enqueue(res.nowNum)
else:
print(f"您的号码:{callNumber},您前面0位")