我是多线程的新手。当对象被另一个线程锁定时,我试图锁定对象,我预计会出现错误并尝试使用 Exception,但它没有用。
class Program
{
static readonly object lockNum = new object();
static int A = 10;
public static void Thread1()
{
lock (lockNum)
{
A = 100;
Console.WriteLine(A);
}
}
public static void Thread2()
{
Thread.Sleep(1000);
lock (lockNum)
{
Thread.Sleep(9000);
Console.WriteLine(A);
Console.WriteLine("Thread 2 is executed");
}
}
public static void Thread3()
{
Thread.Sleep(3000);
try
{
lock (lockNum)
{
Console.WriteLine(A);
Console.WriteLine("Thread 3 is executed");
}
}
catch (Exception ex)
{
Console.WriteLine("Object is locked");
}
}
}
public class MyClass
{
public static void Main()
{
Thread tid1 = new Thread(new ThreadStart(Program.Thread1));
Thread tid2 = new Thread(new ThreadStart(Program.Thread2));
Thread tid3 = new Thread(new ThreadStart(Program.Thread3));
tid1.Start();
tid2.Start();
tid3.Start();
Console.ReadLine();
}
}
Thread2 和 Thread3 在 Thread.Sleep(9000); 之后一起运行,我预计 3 秒后会出现异常,因为该对象仍被 Thread2 锁定。我试图让 Thread3 再次 sleep 3 秒以检查对象是否已解锁(可能是 WriteLine 错误)并重复直到对象被解锁。
请您参考如下方法:
锁不会抛出异常,它们只是等待其他线程释放锁。
如果您想在无法领取锁时跳过代码,您可以使用
if (Monitor.TryEnter(lockNum))
{
Console.WriteLine("No one else had the lock, now it's mine!");
}
else
{
Console.WriteLine("Another thread won :(");
}
您可以选择为该方法提供超时。
