主程序Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace MultiThreadedPrinting
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("********Synchronizing Threads*************");
Printer p = new Printer();
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++)
{
threads[i] = new Thread(new ThreadStart(p.PrintNumber));
threads[i].Name = string.Format("Worker thread #{0}", i);
}
foreach (Thread t in threads)
t.Start();
Console.ReadLine();
}
}
}
类Printer.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace MultiThreadedPrinting
{
public class Printer
{
public void PrintNumber()
{
Console.WriteLine("-> {0} is executing PrintNumbers()", Thread.CurrentThread.Name);
for (int i = 0; i < 10; i++)
{
Random r = new Random();
Thread.Sleep(1000 * r.Next(5));
Console.Write(i + ",");
}
Console.WriteLine();
}
}
}
运行程序你会发现出现意想不到的结果,一些线程可能被挂起,出现了并发的问题。
为了解决并发问题C#提供了特别的关键字:Lock
PrintNumber()
中修改为
lock (this)
{
Console.WriteLine("-> {0} is executing PrintNumbers()", Thread.CurrentThread.Name);
for (int i = 0; i < 10; i++)
{
Random r = new Random();
Thread.Sleep(1000 * r.Next(5));
Console.Write(i + ",");
}
Console.WriteLine();
}