使用python实现单例模式
平常的单例模式,不完美
class Singleto(object):
instance=None
def __init__(self,name):
"""初始化对象"""
self.name=name
def __new__(cls, *args, **kwargs):
"""创建对象"""
if not cls.instance:
cls.instance=object.__new__(cls)
return cls.instance
obj1=Singleto("lwx")
obj2=Singleto('zhangs')
print(obj1,obj2)
解决多线程
import threading
import time
class Singleto(object):
instance=None
lock=threading.RLock()
def __init__(self,name):
"""初始化对象"""
self.name=name
def __new__(cls, *args, **kwargs):
"""创建对象"""
if cls.instance:
return cls.instance
with cls.lock:
if not cls.instance:
time.sleep(0.2) #发生阻塞
cls.instance=object.__new__(cls)
return cls.instance
def task(name):
print( Singleto(name))
for i in range(10):
thread= threading.Thread(target=task,args=str(i))
thread.start()