zoukankan      html  css  js  c++  java
  • Unity创建实例:普通实例,单例,线程单例

    //Unity容器,默认情况下生成普通对象
    //在注册时传入参数new ContainerControlledLifetimeManager(),可以创建单例对象
    //在注册的时候传入参数new PerThreadLifetimeManager(),可以创建线程单例对象
    //容器不知可以生成对象,还可以管理对象的生命周期
    IUnityContainer ucontainer = new UnityContainer();//ContainerControlledLifetimeManager
    ucontainer.RegisterType<IPhone, ApplePhone>(new ContainerControlledLifetimeManager());
    //单例是只要通过容器生成的对象都是同一个实例,在系统中不同地方获取的单利都是同一个实例
    IPhone phone1 = ucontainer.Resolve<IPhone>();
    IPhone phone2 = ucontainer.Resolve<IPhone>();
    Console.WriteLine($"{object.ReferenceEquals(phone1, phone2)}");

    //线程单例:同一个线程就是同一个实例,不同线程就是不同的实例
    IPhone phone1 = null;
    IPhone phone2 = null;
    IPhone phone3 = null;
    IPhone phone4 = null;
    IPhone phone5 = null;
    IUnityContainer ucontainer = new UnityContainer();
    ucontainer.RegisterType<IPhone, AndroidPhone>(new PerThreadLifetimeManager());
    phone1 = ucontainer.Resolve<IPhone>();
    phone2 = ucontainer.Resolve<IPhone>();
    Console.WriteLine($"12的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");

    new Action(() =>
    {
    phone3 = ucontainer.Resolve<IPhone>();
    Console.WriteLine($"3的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");
    }).BeginInvoke(null, null);

    new Action(() =>
    {
    phone4 = ucontainer.Resolve<IPhone>();
    Console.WriteLine($"4的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");
    }).BeginInvoke(arg =>
    {
    phone5 = ucontainer.Resolve<IPhone>();
    Console.WriteLine($"5的当前线程ID:{Thread.CurrentThread.ManagedThreadId}");
    }, null);
    Thread.Sleep(5000);
    Console.WriteLine($"12:{object.ReferenceEquals(phone1, phone2)}");
    Console.WriteLine($"13:{object.ReferenceEquals(phone1, phone3)}");
    Console.WriteLine($"14:{object.ReferenceEquals(phone1, phone4)}");
    Console.WriteLine($"34:{object.ReferenceEquals(phone3, phone4)}");
    Console.WriteLine($"45:{object.ReferenceEquals(phone4, phone5)}");

  • 相关阅读:
    Maven入门
    sdk&jdk&jre
    常用git指令
    Spring 3.x 读书笔记
    JAVA多线程---高并发程序设计
    JAVA多线程---ThreadLocal<E>
    JAVA多线程--Thinking in java
    2017年书单
    正则表达式获取多个img src的值
    使用summernote编辑器上传图片,重写onImageUpload
  • 原文地址:https://www.cnblogs.com/fblogs/p/12263436.html
Copyright © 2011-2022 走看看