每个线程只能访问自己的变量
public readonly ThreadLocal<int> a = new ThreadLocal<int>();
public readonly ThreadLocal<int> b = new ThreadLocal<int>();
//这种声明方式也是一样的
//[ThreadStatic]
//public static int a;
public static void fun1()//定义方法1
{
a.Value= 1;
b.Value = 2;
Console.WriteLine($"a={a} [来自 fun1]");
Console.WriteLine($"b={b} [来自 fun1]");
}
public static void fun2()//定义方法2
{
a.Value = 10;
b.Value = 20;
Console.WriteLine($"a={a} [来自 fun2]");
Console.WriteLine($"b={b} [来自 fun2]");
}
public static void Run()
{
var thread1 = new Thread(fun1);
var thread2 = new Thread(fun2);
thread1.Start();//开始线程1
thread2.Start();//开始线程2
}