'''
Created on 2017-1-11
@author: admin
'''
from threading import Condition, Thread
import time
class CountDownLatch:
def __init__(self,count):
self.count=count
self.condition=Condition()
def await(self):
try:
self.condition.acquire()
while self.count>0:
self.condition.wait()
finally:
self.condition.release()
def countDown(self):
try:
self.condition.acquire()
self.count-=1
self.condition.notifyAll()
finally:
self.condition.release()
if __name__ == '__main__':
class SubThread(Thread):
def __init__(self,name,latch):
Thread.__init__(self)
self.name=name;
self.latch=latch
def run(self):
print("finishing %s"%self.name)
time.sleep(3)
self.latch.countDown()
latch=CountDownLatch(3)
print("start main thread")
thread1=SubThread("thread first",latch)
thread2=SubThread("thread second",latch)
thread3=SubThread("thread third",latch)
thread1.start()
thread2.start()
thread3.start()
latch.await()
print("stop main thread")