线程静态

来源:互联网 发布:2016年网络星期一 编辑:程序博客网 时间:2024/05/16 05:59
 

线程静态就是一个由System.ThreadStaticAttribute属性注释的普通的静态字段。它的存取是根据线程来指定内存位置的,所以它的存取速度较慢。如果一个程序中同时有多个线程同时访问这个字段,则每个线程访问的都是独立的threadvalue 。例如主线程设置它为Master Thread”,线程1设置它为”Thread0”,然后线程2设置它为” Thread1”,主线程读取它的时候,得到的是Master Thread。主线程设置的值在每个线程中是完全隔离的。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. namespace ThreadStaticConsole
  6. {
  7.     class Program
  8.     {
  9.         [ThreadStatic]
  10.         static string data = "unset";
  11.         static void Main(string[] args)
  12.         {
  13.             Console.WriteLine("[Master] before={0}", data);
  14.             data = "Master Thread";
  15.             Console.WriteLine("[Master] after={0}", data);
  16.             Thread[] threads = new Thread[2];
  17.             for (int i = 0; i < 2; i++)
  18.             {
  19.                 threads[i] = new Thread(delegate(object j)
  20.                 {
  21.                     Console.WriteLine("[Thread{0} before={1}", j, data); data = "Thread" + j;
  22.                     Console.WriteLine("[Thread{0}] after={1}", j, data);
  23.                 });
  24.                 threads[i].Start(i);
  25.             }
  26.             Array.ForEach(threads, delegate(Thread th) { th.Join(); });
  27.             Console.WriteLine("[Master] after loop={0}", data);
  28.             Console.ReadLine();
  29.         }
  30.     

运行结果:

[Master] before=unset

[Master] after=Master Thread

[Thread0 before=

[Thread0] after=Thread0

[Thread1 before=

[Thread1] after=Thread1

[Master] after loop=Master Thread


可以看清楚,在设置data前,每个线程看到的data值为null。该注意的是线程静态字段它只由类构造函数初始化一次,并且在只在第一次引用该字段的线程上,其他线程再访问这个字段时,为字段的类型的默认值(defalut(T)