代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static int x = 0;
private static object _obj = new object();
static void Main(string[] args)
{
for (int i = 0; i < 1; i++)
{
Thread thread = new Thread(new ThreadStart(test));
thread.Start();
}
Thread.Sleep(2000);
Thread thread1 = new Thread(new ThreadStart(test1));
thread1.Start();
Thread.Sleep(2000);
Thread thread2 = new Thread(new ThreadStart(test));
thread2.Start();
Thread.Sleep(2000);
Thread thread3 = new Thread(new ThreadStart(test3));
thread3.Start();
Console.ReadKey();
}
static void test()
{
try
{
Monitor.Enter(_obj);
if (x > 0)
{
Console.WriteLine("开始等待");
Monitor.Wait(_obj);
// Monitor.Wait(_obj, 5000);这是我设置的等待5秒继续执行
Console.WriteLine("线程3释放了锁定对象,等待已结束,现在退出!");
}
x--;
Console.WriteLine(x);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
}
catch (Exception ex)
{
throw;
}
finally
{
Monitor.Pulse(_obj);
Monitor.Exit(_obj);
}
}
static void test1()
{
x = 2;
}
static void test3()
{
Console.WriteLine("线程3进入,开始释放锁定对象!");
Monitor.Enter(_obj);
Monitor.Pulse(_obj);
Monitor.Exit(_obj);
Console.WriteLine("线程3已释放了锁定对象!");
}
}
}