net 多线程学习 14 线程本地变量 ThreadLocal

多线程安全的本地线程变量

每个线程只能访问自己的变量


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
}


作者:spike

分类: Net

创作时间:2023-06-25

更新时间:2024-12-09

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1