单例模式多线程

单例模式 : 确保某个类只有一个实例化对象

import  time
class A:
    from threading import Lock
    __instance = None
    lock = Lock()
    def __new__(cls, *args, **kwargs):
        #加锁确保时间片不发生轮转
        with cls.lock:
            if not cls.__instance:
                #在这里time.sleep强制发生了时间片的轮转,下一次时间片轮上创建一个新对象
                time.sleep(0.0000001)
                cls.__instance = super().__new__(cls)
        return cls.__instance

def func():
    a = A()
    print(a)

from threading import Thread
for i in range(10):
    Thread(target=func).start()

 

posted @ 2021-02-04 20:18  苦行僧冬*婷  阅读(55)  评论(0)    收藏  举报