Lock object:
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 object:
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()
In the Lock object example, after ten threads are started, one thread is locked and other threads are blocked. Only after unlocking, other threads will be released.
In the Condition object example, the merchant waits for the customer thread to purchase if the goods are sufficient, and informs the customer thread to purchase when the goods are not enough.