static int i = 0;
static void Main()
{
ThreadTest tt = new ThreadTest();
new Thread(tt.Incr).Start();
tt.I();
tt.I2();
}
void Incr()
{
for(int x = 0; x < 3; x++)
{
Console.WriteLine(i);
i++;
}
}
void I()
{
while(i <= 3)
{
if(i==3)
break;
Console.WriteLine("Value of i in I:{0}",i);
}
}
void I2()
{
Console.WriteLine("\t\tFinally i is:{0}\n\n",i);
}
I have run this piece of code about a few hundred times now and find that I2 always executes last. Why does this happen? May be a few hundred times is not enough to see the true unpredictability of threads?
Well,
I2()is the last method inMain()and it is not threaded in any way.So what’s the question, why the thread finishes earlier?
That’s because
I2()is run afterI()and the while-loop inI()effectively waits for the thread to finish first.