using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Dome1
{
class Program测
{
static int Money = 10000;
static Object objectLock = new Object();
//线程安全 线程同步
//线程安全可以被多个线程随意调用
[MethodImpl(MethodImplOptions.Synchronized)]//方法3 方法使用
static void GetMoney(object name)
{
while(true)
{
//lock (objectLock)//方法1 lock(objectLock){...}
//{
try
{
Monitor.Enter(objectLock);//方法2 等待没人锁定locker对象 我就锁定他 然后继续执行
Console.WriteLine(name + "查看余额:" + Money);
int yu = Money - 1;
Console.WriteLine(name + "取钱");
Money = yu;
Console.WriteLine(name + "取钱还剩:" + Money);
}
finally
{
Monitor.Exit(objectLock);//最后释放
}
//}
}
}
static void Main(string[] args)
{
//线程同步
//Thread th = new Thread(GetMoney);
//th.Start("张飞");
//方法四
ManualResetEvent manualResetEvent = new ManualResetEvent(false);
Thread th2 = new Thread(() => {
while (true)
{
Console.WriteLine("等着开门");
//manualResetEvent.WaitOne();
//Console.WriteLine("等到开门了");
//设置等待时间
if (manualResetEvent.WaitOne(5000))//等5s 如果没有等到 manualResetEvent.Set(); false
{
Console.WriteLine("终于等到你");
}
else
{
Console.WriteLine("等到5s还没到");
}
}
});
th2.Start();
Console.WriteLine("按任意键开门");
Console.ReadKey();
manualResetEvent.Set();
Thread.Sleep(5000);
manualResetEvent.Reset();
Console.ReadKey();
}
}
}
//线程池 创建线程比较消耗资源 线程池有一堆创建好的线程
//ThreadPool.QueueUserWorkItem(state => {
//},"00");
//方法中如果有await 则方法必须标记为async 不是所有方法都可以被轻松的标记为async Winform中事件处理方法都可以标记为async
//MVC中的Action也可以标记为async 控制台 Main方法不可以标记为async
//TPL特点 方法都以XXXAsync结尾,结果返回都是一个泛型Task<T>
private async void ReadMethod()
{
using (FileStream fs = File.OpenRead("D;/1.txt"))
{
byte[] buff = new byte[64];
await fs.ReadAsync(buff, 0, buff.Length);
//等价于
//Task<int> task = fs.ReadAsync(buff, 0, buff.Length);//TPL
//task.Wait();
string s = Encoding.UTF8.GetString(buff);
}
}
C#中多线程及线程锁
最新推荐文章于 2025-08-01 17:32:52 发布