User-307604573 posted
I have written a code which is as below:I am not able to understand the out as I get output different.
The code:
class Class6
{
static StringBuilder text = new StringBuilder();
public static void Main()
{
Thread firstThread = new Thread(new ThreadStart(Fun1));
Thread secondThread = new Thread(new ThreadStart(Fun2));
firstThread.Start();
secondThread.Start();
firstThread.Join();
secondThread.Join();
Console.WriteLine("Text is:\r\n{0}", text.ToString());
}
public static void Fun1()
{
lock(text)
{
for(int i=1; i<=200; i++)
{
Thread.Sleep(10);
text.Append("First Threadd \n "+i.ToString() + " ");
}
}
}
public static void Fun2()
{
lock(text)
{
for(int i=21; i<=400; i++)
{
Thread.Sleep(2);
text.Append("second thread \n"+i.ToString() + " ");
}
}
}
}
}
here when I have iteration which is small numbers then it works fine with LOCK.
But as loop is for larger value which is in the code,then output varies at times it shows only First thread or only second thread wherein again
numbers displayed are not as per given in the loop.It skips many numbers and it is very unpredictable output.Can anyone explain correctly.
why it is the case..Should I Use Monitor class instead....
Thanks in advance