Lock对象:
import threading
import time
class myThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global x
lock.acquire() #当前线程锁定,阻塞其他线程
for i in range(10):
x+=1
time.sleep(2)
print("x=",x)
lock.release() #当前线程解锁,释放其他线程
x=0
lock=threading.Lock() #创建Lock对象
t=list()
for i in range(10): #列表t追加10个线程类
t1=myThread()
t.append(t1)
for i in t:
i.start()
print(i)
Condition对象:
import threading
class business(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global goods
while True:
con.acquire()
if goods==10: #货物足够,商家等待购买
print("Goods={0} , business wait...".format(goods))
con.wait()
print("business resume")
goods+=10 #商家补货
print("business replenish")
con.notify_all()
con.release()
class customer(threading.Thread):
def __init__(self,name):
threading.Thread.__init__(self)
self.name=name
def run(self):
global goods
con.acquire()
if goods==0: #货物不够,买家等待补充
print("Goods={0} {1} wait...".format(goods,self.name))
con.wait()
print("{0} resume".format(self.name))
goods-=10 #买家购买
print("{0} finished, Goods={1}".format(self.name,goods))
con.notify_all()
con.release()
goods=10
con=threading.Condition() #创建Condition对象
b=business()
c1=customer('C1')
c2=customer('C2')
c1.start()
b.start()
c2.start()
Lock对象例子中,十个线程开始后,一个线程锁定,其他线程阻塞,只有解锁后其他线程才会被释放。
Condition对象例子中,商家货物足够则等待顾客线程购买,货物不够则补充后通知顾客线程购买。