using System;
using System.Threading;
class LockDemo
{
private static int number = 0;
private static object lockObject = new object();
private static void DoSomething()
{
while (true)
{
lock (lockObject)
{
int originalNumber = number;
number += 1;
Thread.Sleep((new Random()).Next(1000)); // sleep for a random amount of time
number += 1;
Thread.Sleep((new Random()).Next(1000)); // sleep again
Console.Write("Expecting number to be " + (originalNumber + 2).ToString());
Console.WriteLine(", and it is: " + number.ToString());
// without the lock statement, the above would produce unexpected results,
// since the other thread may have added 2 to the number while we were sleeping.
}
}
}
public static void Main()
{
Thread t = new Thread(new ThreadStart(DoSomething));
t.Start();
DoSomething(); // at this point, two instances of DoSomething are running at the same time.
}
}
0 comments:
Đăng nhận xét