local 本地独立
CLR为每个线程分配自己的内存栈(stack) 以便是本地变量保持独立
for Text
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsolePlan
{
class Program
{
private static TimeSpan SleepTime = new TimeSpan(0, 0, 1);
private const string MainThreadName = "MainThread";
static void Main(string[] args)
{
Thread.CurrentThread.Name = MainThreadName;
Thread thread = new Thread(Text);
thread.Name = "SubThread";
thread.Start();
Text();
Console.ReadKey(true);
}
static void Text()
{
Console.WriteLine("【{0}】",Thread.CurrentThread.ManagedThreadId);
for (int idx = 0; idx < 100; idx++)
{
if (Thread.CurrentThread.Name==MainThreadName)
{
Console.Write(idx + "_main\t");
}
else
{
Console.Write(idx + "\t");
}
}
Console.WriteLine("---------------------------------------");
}
}
}
运行结果;
结果分析:可知两个线程的变量是各个独立的。
Shared 共享:
- 如果多个线程都引用同一个对象的实例,那么他们就共享数据。
- 被lambda表达式或者匿名委托捕获的本地变量,会被编译器转化成字段(field) 所以也会被共享
- 静态字段(file)也会在线程间共享数据。
for Text one
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsolePlan
{
class Program
{
private bool IsDone = false;
private const string MainThreadName = "MainThread";
static void Main(string[] args)
{
Program pr = new Program();
Thread.CurrentThread.Name = MainThreadName;
Thread thread = new Thread(pr.GoTo);
thread.Name = "SubThread";
thread.Start();
//主线程调用方法
pr.GoTo();
Console.ReadKey(true);
}
void GoTo()
{
if (IsDone )
{
Console.WriteLine("?");
}
else
{
Thread.Sleep(100);
IsDone = true;
Console.WriteLine("#");
}
}
}
}
如果在方法里线程不睡100ms结果又会不一样。用到共享资源需要临界边缘处理。加锁 lock(Isdone)
for text two
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsolePlan
{
class Program
{
private const string MainThreadName = "MainThread";
static void Main(string[] args)
{
bool IsDone = true;
int i = 0;
ThreadStart pro = () => {
for (; i < 10; i++)
{
Console.Write(i + "\t");
}
if (IsDone)
{
IsDone = false;
Console.WriteLine(IsDone);
}
};
Program pr = new Program();
Thread.CurrentThread.Name = MainThreadName;
Thread thread = new Thread(pro);
thread.Name = "SubThread";
thread.Start();
//主线程调用方法
pro();
Console.ReadKey(true);
}
}
}
运行结果截图:
可以看出在主线程进入方法匿名委托以后,主方法的内的i 和IsDone被捕获,第二次进来以后变量值没有释放。
反编译可以看出源码编译的代码: