天天看点

对多线程同步的研究.

同事观点:静态方法中,如果两个线程同时访问一个静态函数,该函数中的变量值会出现不同步.

做了一个试验.结论如下:

如果该静态类中没有静态成员,那么和非静态类是一样的.

using System;

using System.Threading;

public class Example

{

 private static string sss = "hello " + System.DateTime.Now.ToString() ;

 public static void Main()

 {

  for ( int i= 0;i<2 ;i++)

  {

   Console.WriteLine( System.DateTime.Now.ToString() ) ;

    Thread th = new Thread( new ThreadStart( proc) ) ;

   th.Start();

   Thread.Sleep(1000);

  }

  }

 public static void proc()

 {

  string str = "hello " + System.DateTime.Now.ToString() ;

//第一个,第二个线程先后到达这里,并阻塞.如果显示时间一致,说明后到的把先到的变量值覆盖了.

  Thread.Sleep(1000);

  Console.WriteLine( str ) ;

 }