在上一篇介绍多线程的基本知识中有一段代码,通过略微修改并运行,理解了多线程对变量的共享和独享。
namespace MultiThread
{
class SynchronizationThreadsExample
{
private int counter = 0; //成员变量被多个线程共享
static void Main(string[] args)
{
SynchronizationThreadsExample STE = new SynchronizationThreadsExample();
STE.ThreadFunction();
Console.ReadLine();
}
public void ThreadFunction()
{
Thread DummyThread = new Thread(new ThreadStart(SomeFunction));
DummyThread.IsBackground = true;
DummyThread.Name = "First Thread";
DummyThread.Start();
Console.WriteLine("Started thread {0}", DummyThread.Name);
Thread DummyPriorityThread = new Thread(new ThreadStart(SomeFunction));
DummyPriorityThread.IsBackground = true;
DummyPriorityThread.Name = "Second Thread";
DummyPriorityThread.Start();
Console.WriteLine("Started thread {0}", DummyPriorityThread.Name);
DummyThread.Join();
DummyPriorityThread.Join();
}
public void SomeFunction()
{
try
{
while (counter < 10)
{
int tempCounter = counter; //tempCounter 被当前线程独享
tempCounter++;
Console.WriteLine("Thread . SomeFunction-tempCounter: " + Thread.CurrentThread.Name + tempCounter);
Console.WriteLine("*************");
Thread.Sleep(1000); //时间设成1000ms,可以很好的看出两个线程的交替运行
counter = tempCounter;
Console.WriteLine("Thread . SomeFunction-counter: " + Thread.CurrentThread.Name + counter);
}
}
catch (ThreadInterruptedException Ex)
{
Console.WriteLine("Exception in thread " + Thread.CurrentThread.Name);
}
finally
{
Console.WriteLine("Thread Exiting. " + Thread.CurrentThread.Name);
}
}
}
}
小结:类的成员变量被多个线程共享;类中成员函数的局部变量被单个当前线程独享。