namespace MultiThread
{
class SynchronizationThreadsExample
{
private int counter = 0; //被多个线程共享
private object lockObject = new object();
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)
{
counter++;
Thread.Sleep(1);
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);
}
}
}
}
运行结果:
Started thread First Thread
Thread . SomeFunction-counter: First Thread1
Thread . SomeFunction-counter: First Thread2
Thread . SomeFunction-counter: First Thread3
Started thread Second Thread
Thread . SomeFunction-counter: First Thread4
Thread . SomeFunction-counter: First Thread5
Thread . SomeFunction-counter: First Thread7
Thread . SomeFunction-counter: Second Thread7
Thread . SomeFunction-counter: First Thread9
Thread . SomeFunction-counter: Second Thread9
Thread Exiting. Second Thread
Thread . SomeFunction-counter: First Thread10
Thread Exiting. First Thread
将上边黄色代码加锁,具体如下,结果将发生变化:
lock(this.lockObject)
{
counter++;
Thread.Sleep(1);
Console.WriteLine("Thread . SomeFunction-counter: " + Thread.CurrentThread.Name + counter);
}
运行结果如下:
Started thread First Thread
Thread . SomeFunction-counter: First Thread1
Thread . SomeFunction-counter: First Thread2
Started thread Second Thread
Thread . SomeFunction-counter: First Thread3
Thread . SomeFunction-counter: First Thread4
Thread . SomeFunction-counter: Second Thread5
Thread . SomeFunction-counter: Second Thread6
Thread . SomeFunction-counter: Second Thread7
Thread . SomeFunction-counter: Second Thread8
Thread . SomeFunction-counter: Second Thread9
Thread . SomeFunction-counter: First Thread10
Thread Exiting. First Thread
Thread . SomeFunction-counter: Second Thread11
Thread Exiting. Second Thread