代码之家  ›  专栏  ›  技术社区  ›  fernandos fernandos

线程安全方法调用

  •  1
  • fernandos fernandos  · 技术社区  · 10 年前

    请让我知道以下方法调用是否线程安全。 我在主线程上调用ThreadStartMain,创建新线程并在新实例上调用A_GetCounryName方法。

    由于我总是通过新实例调用,所以我认为这是线程安全的,即使我在某些类中有实例变量。

     class MyThread
        {
            private void ThreadStartMain()
            {
                for (int i = 0; i < 5; i++)
                {
                    A a = new A();
                    ThreadStart start = new ThreadStart(a.A_GetCounryName);
                    Thread t = new Thread(start);
                    t.Start();
                }
            }
        }
    
        class A
        {
            public B GetNewObject()
            {
                B bObj = new B();
                return bObj;
            }
    
            public void A_GetCounryName()
            { 
                B b=GetObject();
                string cName=b.B_GetCoutryName();
            }
        }
    
        class B
        {
            C cObj = null;
    
            public B()
            {
                cObj = new C();
                cObj.Prop1 = 1;
                cObj.Prop1 = 2;
                cObj.Prop1 = 3;
            }
    
            public string B_GetCoutryName()
            {
               string countryName= cObj.C_GetCoutryName();
               return countryName;
            }
        }
    
    
        class C
        {
            public int Prop1 { get; set; }
            public int Prop2 { get; set; }
            public int Prop3 { get; set; }
    
            public string C_GetCoutryName()
            {
                string name = "Italy";
                return name;
            }
        }
    
    1 回复  |  直到 10 年前
        1
  •  1
  •   usr    10 年前

    是的,这是安全的,因为您的线程不共享状态。更准确地说:它们不访问公共存储位置。