多线程应用程序变量共享

时间:2017-06-21 07:33:36

标签: c# multithreading oop

为了检查不同线程如何引用/共享变量(在我的示例中#34; connection"),我编写了以下代码,我发现每个线程都有自己的连接(执行DoAnotherTask方法) 。

我想了解运行时如何处理这个问题,当一个线程进入CreateSharedConnection静态方法时,每个线程是否创建自己的变量副本并指向适当的对象?

 public static void StartThreadTest()
    {
        System.Threading.Thread thread1 = new System.Threading.Thread(new System.Threading.ThreadStart(CreateSharedConnection));
        thread1.Name = "Thread 1";
        thread1.Start();

        System.Threading.Thread.Sleep(1000);
        //Second Thread Going before First is completed with connection.
        System.Threading.Thread thread2 = new System.Threading.Thread(new System.Threading.ThreadStart(CreateSharedConnection));
        thread2.Name = "Thread 2";
        thread2.Start();

        System.Threading.Thread.Sleep(1000);
        //Third Thread Going before Second is completed with connection.
        System.Threading.Thread thread3 = new System.Threading.Thread(new System.Threading.ThreadStart(CreateSharedConnection));
        thread3.Name = "Thread 3";
        thread3.Start();

        System.Threading.Thread.Sleep(1000);
        //Fourth Thread Going before Third is completed with connection.
        System.Threading.Thread thread4 = new System.Threading.Thread(new System.Threading.ThreadStart(CreateSharedConnection));
        thread4.Name = "Thread 4";
        thread4.Start();

    }



    /// <summary>
    /// This is to start multiple threads.
    /// </summary>
    public static void CreateSharedConnection()
    {
        ThreadingPractice.GenericConnection connection= new ThreadingPractice.GenericConnection();

        connection.DoTaskWithSleep();

        //First Thread should invoke it again once second Thread has created a new connection after 1 Second.

        connection.DoAnotherTask();
 }

通用连接类:

  public class GenericConnection
{
   public long ObjectIdentifier = 0;

   public GenericConnection()
   {
       ObjectIdentifier = System.DateTime.Now.Ticks;
       Console.WriteLine("Thread: " + System.Threading.Thread.CurrentThread.Name + "Generic Connection has been created at: " + DateTime.Now.ToString() + " with Unique Identifier of " + ObjectIdentifier.ToString());
   }

   /// <summary>
   /// This method is kept to make a call stuck for few seconds as if doing a IO intensive Query.
   /// </summary>
   public void DoTaskWithSleep()
   {
       System.Threading.Thread.Sleep(2000);
       Console.WriteLine("Thread: " + System.Threading.Thread.CurrentThread.Name + " Sleep has been done at: "+ System.DateTime.Now.ToString() + " This object has identifier as ##" + ObjectIdentifier.ToString());           
   }


   public void DoAnotherTask()
   {
       System.Threading.Thread.Sleep(1000);
       Console.WriteLine("Thread: " + System.Threading.Thread.CurrentThread.Name + "Done another task at: " + System.DateTime.Now.ToString() + " This object has identifier as ##" + ObjectIdentifier.ToString());   
   }

}

0 个答案:

没有答案