#encoding=utf8import threading
import time
#这里使用方法__new__来实现单例模式classSingleton(object):#抽象单例def__new__(cls,*args,**kw):ifnothasattr(cls,'_instance'):orig =super(Singleton, cls)cls._instance = orig.__new__(cls,*args,**kw)return cls._instance
#总线classBus(Singleton):lock = threading.RLock()defsendData(self,data):self.lock.acquire()time.sleep(3)print"Sending Signal Data...",dataself.lock.release()#线程对象,为更加说明单例的含义,这里将Bus对象实例化写在了run里classVisitEntity(threading.Thread):my_bus=""name=""defgetName(self):return self.namedefsetName(self, name):self.name=namedefrun(self):self.my_bus=Bus()self.my_bus.sendData(self.name)if __name__=="__main__":for i inrange(3):print"Entity %d begin to run..."%imy_entity=VisitEntity()my_entity.setName("Entity_"+str(i))my_entity.start()