Answer the question
In order to leave comments, you need to log in
Why doesn't the second thread start when using the TryEnter() construct?
using System;
using System.Threading;
class Demo
{
static int Count;
static object Locker = new object();
static void Main()
{
Thread ob = new Thread(Run);
ob.Name = "first ";
Thread ob1 = new Thread(Run);
ob1.Name = "second ";
ob.Start();
ob1.Start();
ob.Join();
ob1.Join();
}
public static void Run()
{
if (Monitor.TryEnter(Locker))
{
do
{
Thread.Sleep(100);
Console.WriteLine(Thread.CurrentThread.Name + " вошел " + Count);
Count++;
} while (Count < 10);
Console.WriteLine(Thread.CurrentThread.Name + " закончил свою работу");
Count = 0;
Monitor.Exit(Locker);
}
else
{
Console.WriteLine("Не вошел " + Thread.CurrentThread.Name);
}
}
}
Answer the question
In order to leave comments, you need to log in
Well, apparently because the second thread failed to capture the lock, it went to the else branch and, after displaying the message, completed its work, because there are no more instructions in the body of the Run function.
It's strange that you ask this if you wrote this code.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question