直接新建一个类,copy过去查看
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Common
{
public class L_Thread
{
#region lock [对象锁] https://www.cnblogs.com/gyjjyg/p/6834167.html
// [对象锁,锁的对象]定义一个保证线程同步的标识 不能为Null 不能是string类型(引用类型)
private static object lockobj_Lock = new object();
public static void LockThread_Lock(object name)
{
// 当第一个线程执行到此,对locker对象 "加锁",
// 当第二个线程执行到此,如果检测到locker对象为"加锁"状态,该线程就会挂起等待第一个线程解锁后再继续执行
// lock语句执行完也即代表上一个线程执行结束,同时对该对象"解锁"
lock (lockobj_Lock)
{
#region 需要锁定的代码块
Console.WriteLine(name + " 锁5秒开始");
Thread.Sleep(5 * 1000);
Console.WriteLine(name + " 锁5秒结束");
#endregion 需要锁定的代码块
}
}
public static void LockThread_Lock_Show()
{
Thread thread = new Thread(new ParameterizedThreadStart(LockThread_Lock));
thread.IsBackground = true;
thread.Start("first");
Thread.Sleep(2 * 1000); // 睡两秒
Thread thread2 = new Thread(new ParameterizedThreadStart(LockThread_Lock));
thread2.IsBackground = true;
thread2.Start("second");
}
#endregion
#region Mutex [标识锁,标识相同等,不同异步; (这里默认的标识 = "Mutex|666") ]
public static void LockThread_Mutex(object name = null)
{
if (name == null) name = "Mutex|666";
using (Mutex mute = new Mutex(false, name+""))
{
try
{
mute.WaitOne();
Console.WriteLine(name + " 锁5秒开始");
Thread.Sleep(5 * 1000);
//throw new Exception("试试");
//return;
Console.WriteLine(name + " 锁5秒结束");
}
catch (Exception e)
{
mute.ReleaseMutex();
Console.WriteLine("\n\nMutex报错!" + e.Message + "\n\n");
//throw e;
}
finally
{
mute.ReleaseMutex();
}
}
}
public static void LockThread_Mutex_Show()
{
Thread thread = new Thread(new ParameterizedThreadStart(LockThread_Mutex));
thread.IsBackground = true;
thread.Start("first");
Thread.Sleep(1 * 1000); // 睡一秒
Thread thread2 = new Thread(new ParameterizedThreadStart(LockThread_Mutex));
thread2.IsBackground = true;
thread2.Start("first");
Thread.Sleep(1 * 1000); // 睡一秒
Thread thread3 = new Thread(new ParameterizedThreadStart(LockThread_Mutex));
thread3.IsBackground = true;
thread3.Start("third");
}
#endregion
#region Monitor 基本同lock
private static object lockobj_Monitor = new object(); //锁的对象
public static void LockThread_Monitor_lock()
{
Monitor.Enter(lockobj_Monitor); //锁对象
Console.WriteLine("Monitor锁了");
}
public static void LockThread_Monitor_unlock()
{
Monitor.Exit(lockobj_Monitor); //解锁对象
Console.WriteLine("Monitor解锁了");
}
public static void LockThread_Monitor_Show()
{
Thread thread = new Thread(new ParameterizedThreadStart(LockThread_Monitor));
thread.IsBackground = true;
thread.Start("first");
Thread.Sleep(2 * 1000); // 睡两秒
Thread thread2 = new Thread(new ParameterizedThreadStart(LockThread_Monitor));
thread2.IsBackground = true;
thread2.Start("second");
}
public static void LockThread_Monitor(object name)
{
LockThread_Monitor_lock();
Console.WriteLine(name + " 锁5秒开始");
Thread.Sleep(5 * 1000);
Console.WriteLine(name + " 锁5秒结束");
LockThread_Monitor_unlock();
}
#endregion
}
}