using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication4
{
class DataBase
{//----------数据库更新类,模仿数据库更新
public void DbSave(string str)
{
try
{
Monitor.Enter(this);
for (int i = 0; i < 10; i++)
{
Thread.Sleep(100);
Console.WriteLine(str);
}
}
finally
{
Monitor.Exit(this);
}
Console.WriteLine("数据库更新完成");
}
}
class Program
{
static DataBase db = new DataBase();
public static void Work1()
{
Console.WriteLine("线程1开始工作了");
db.DbSave("线程1开始更新数据库。。。");
Console.WriteLine("============>线程1完成工作了<============.");
}
public static void Work2()
{
Console.WriteLine("线程2开始工作了");
db.DbSave("线程2开始更新数据库。。。");
Console.WriteLine("============>线程2完成工作了<============.");
}
static void Main(string[] args)
{
Thread th1 = new Thread(new ThreadStart(Work1));
Thread th2 = new Thread(new ThreadStart(Work2));
th1.Start();
th2.Start();
Console.ReadKey();
}
}
}
去掉红色和绿色的代码。。会引发两个线程同时更新数据库。。
去掉红色代码。。将引发异常(具体未知,有待测试)。。
另外一种方法。用C#提供的Lock语句
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication4
{
class DataBase
{//----------数据库更新类,模仿数据库更新
public void DbSave(string str)
{
lock (this)
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(100);
Console.WriteLine(str);
}
}
Console.WriteLine("数据库更新完成");
}
}
class Program
{
static DataBase db = new DataBase();
public static void Work1()
{
Console.WriteLine("线程1开始工作了");
db.DbSave("线程1开始更新数据库。。。");
Console.WriteLine("============>线程1完成工作了<============.");
}
public static void Work2()
{
Console.WriteLine("线程2开始工作了");
db.DbSave("线程2开始更新数据库。。。");
Console.WriteLine("============>线程2完成工作了<============.");
}
static void Main(string[] args)
{
Thread th1 = new Thread(new ThreadStart(Work1));
Thread th2 = new Thread(new ThreadStart(Work2));
th1.Start();
th2.Start();
Console.ReadKey();
}
}
}