在学习多线程的时候,我们经常要学习到多窗口售票这一经典案例,今天我们将用Python语言写一个简单易懂的售票程序,帮助大家学习理解
import threading
import time
lock=threading.Lock()
k=250
class a(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global k,lock
while(k>0):
lock.acquire()
if(k>0):
print("a窗口卖出一张票,还剩"+str(k-1)+"张票")
k=k-1
if(k<0 and k==0):
print("票卖完了")
lock.release()
class b(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global k,lock
while(k>0):
lock.acquire()
if(k>0):
print("b窗口卖出一张票,还剩"+str(k-1)+"张票")
k=k-1
if(k<0 and k==0):
print("票卖完了")
lock.release()
t1=a()
t1.start()
t2=b()
t2.start()