我已经创建了 3 个线程,并且所有线程都对 thread1 之外的 threadlocal 属性进行了增量操作。我还在 threadlocal 委托中通过值 11 初始化 threadstatic 属性。这里我总是在第一个线程中获得 num = 0 的值。为什么这样?
class Program
{
//static int numDuplicate = 0;
[ThreadStatic]
static int num = 5;
public static ThreadLocal<int> _field = new ThreadLocal<int>(() =>
{
num = 11;
//numDuplicate = num;
Console.WriteLine("Threadstatic variable value in Threadlocal's delegate = " + num.ToString());
return Thread.CurrentThread.ManagedThreadId;
});
public static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(() =>
{
Console.WriteLine("Threadlocal attribute value for thread 1: " + _field + ". Threadstatic variable value = " + num.ToString());
}));
Thread t2 = new Thread(new ThreadStart(() =>
{
_field.Value++;
Console.WriteLine("Threadlocal attribute value for thread 2: " + _field + ". Threadstatic variable value = " + num.ToString());
}));
Thread t3 = new Thread(new ThreadStart(() =>
{
_field.Value++;
Console.WriteLine("Threadlocal attribute value for thread 3: " + _field + ". Threadstatic variable value = " + num.ToString());
}));
t1.Start();
t2.Start();
t3.Start();
Console.ReadLine();
}
}
//Output:
Threadstatic variable value in Threadlocal's delegate = 11
Threadstatic variable value in Threadlocal's delegate = 11
Threadstatic variable value in Threadlocal's delegate = 11
Threadlocal attribute value for thread 1: 10. Threadstatic variable value = 0
Threadlocal attribute value for thread 3: 13. Threadstatic variable value = 11
Threadlocal attribute value for thread 2: 12. Threadstatic variable value = 11