📄 class1.cs
字号:
using System;
using System.Threading;
class ThreadLock
{
private int ctr=50;
public static void Main()
{
ThreadLock tt=new ThreadLock();
Thread th1=new Thread(new ThreadStart(tt.Decrease));
th1.IsBackground=true;
th1.Name="Thread1";
Thread th2=new Thread(new ThreadStart(tt.Decrease));
th2.IsBackground=true;
th2.Name="Thread2";
th1.Start();
th2.Start();
th1.Join();
th2.Join();
//所有线程结束后,输出一条信息
Console.WriteLine("所有线程结束");
}
public void Decrease()
{
Console.WriteLine("{0}正在运行...",Thread.CurrentThread.Name);
while(true)
{
Monitor.Enter(this);
if(ctr>=10)
{
int temp=ctr;
temp-=10;
Thread.Sleep(1000);//模拟进行一些处理
ctr=temp;
/*
for(int i=1;i<=10;i++)
{
Interlocked.Decrement(ref ctr);
}
*/
//Thread.Sleep(1000);//模拟进行一些处理
Console.WriteLine("{0}调度车皮,还剩车皮数量:{1}",Thread.CurrentThread.Name,ctr);
Monitor.Exit(this);
}
else
{
Console.WriteLine("车皮数据量不够,{0}调度错误",Thread.CurrentThread.Name);
Monitor.Exit(this);
break;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -