多线程—卖票

2020-01-20 10:42:15 浏览数 (1)

题目:python3多线程

代码语言:javascript复制
import threading
import time
list_ticket=[]      #定义票池
lock=threading.Lock() #获得多线程锁
num=30#票数
for i in range(1,num 1):
     #ticket_num="0"*(len(str(num))-len(str(i))) str(i)    #001,003,013
     ticket_num=str(i).zfill(3)
     list_ticket.append(ticket_num)
# print(list_ticket)
def seel_ticket(num):  # 通过传参来用窗口买票
    #全局变量
   # global list_ticket
   #time.sleep(1)
   while len(list_ticket)>0:
       #time.sleep(0.5)
       lock.acquire()      #打开线程锁
       print("正在打印票")
       thre = list_ticket[0]   #依次买票
       print(num,"号窗口售票点出票成功,票号为:",thre )
       del list_ticket[0]   #取出以后就得马上删除
       lock.release()      #释放
       time.sleep(0.1)    # 必须有这个睡眠
#      ===========================================================
# #新建线程
# list_thread=[]   # 线程的集合
for i in range(5):
    thread = threading.Thread(target=seel_ticket, args=(i 1,)).start()
    # list_thread.append(thread)
# for i in list_thread:
#     i.start()


# #创建5个线程
# thread=threading.Thread(target=seel_ticket,args=(1,))
# thread2=threading.Thread(target=seel_ticket,args=(2,))
# thread3=threading.Thread(target=seel_ticket,args=(3,))
# thread4=threading.Thread(target=seel_ticket,args=(4,))
# thread5=threading.Thread(target=seel_ticket,args=(5,))
# #启动
# thread.start()
# thread2.start()
# thread3.start()
# thread4.start()
# thread5.start()

0 人点赞