pyhon __new__单例2.py

# class Singleton:
#     _instance = None
#
#     def __init__(self):
#         print("init")
#
#     @classmethod
#     def get_instance(cls):
#         if cls._instance is None:
#             cls._instance =cls()
#         return cls._instance
#
#
# if __name__ == "__main__":
#     a = Singleton.get_instance()
#     b = Singleton.get_instance()
#
#     print(a is b)

"""
运行结果
init
True
 这是一个实现方法,获取当前实例,但是可以正常实例化它,因此它不会成为单例对象。

"""

# 使用__new__ 创建实例,在创建类实例的时候会调用此方法,此方法在__init__之前已经调用过。
#
# class Singleton:
#     _instance =None
#
#     def __init__(self):
#         print("init")
#
#     def __new__(cls, *args, **kwargs):
#         if cls._instance is None:
#             cls._instance = super().__new__(cls)
#         return cls._instance
#
#
# if __name__ == '__main__':
#     a = Singleton()
#     b = Singleton()
#     print(a is b)  # True
# 以上两种方式都不是线程安全 ,淫才十七称为线程安全,让我们LOCK y引入

import threading
import time
class ThreadingSingleton:
_instance =None
_lock=threading.Lock()
def __init__(self,name):
time.sleep(3)
self.name= name
# print("init")
def __new__(cls, *args, **kwargs):
with cls._lock:
if cls._instance is None:
cls._instance =super().__new__(cls)
return cls._instance
def __str__(self):
return str(self.name)

if __name__ == '__main__':

for i in range(10):
# print("i", i)
my = ThreadingSingleton(i)
print(my)

# 简单实用也安全实现线程模式,在初始化的时候 停止三秒 线程依然按照顺序执行,。

0
1
2
3
4
5
6
7
8
9

 

posted @ 2020-05-02 20:35  Xingtxx  阅读(128)  评论(0编辑  收藏  举报