I want to implement a multithread system (two threads will do) and I followed a tutorial
Thread t1 = new Thread(new ThreadStart(threadA));
Thread t2 = new Thread(new ThreadStart(threadB));
t1.Start();
t2.Start();
The output is unexpected for me as it shows:
"threadA"
"threadA"
"threadA"
"threadB"
"threadB"
"threadB".
Is something wrong with my code? Many thanks.
This is happening because in the time that it takes for you to go from t1.Start()
to t2.Start()
, your t1
has already completed.
Try something like this if you want to see your code alternate a little
Thread t1 = new Thread(
new ThreadStart(()=>
{
for(int i = 0; i < 3; i++)
{
System.Console.WriteLine("ThreadA");
Thread.Sleep(3000)
}
}));
Thread t2 = new Thread(
new ThreadStart(()=>
{
for(int i = 0; i < 3; i++)
{
System.Console.WriteLine("ThreadB");
Thread.Sleep(1000)
}
}));
t1.Start();
t2.Start();
It should print something like this:
ThreadA
ThreadB
ThreadB
ThreadA
ThreadB
ThreadA
However, this just shows that you cannot guarantee any order when it comes to threading.
The short of it is that threads execute when the CLR and OS schedule them to do so, based on a lot of implementation details that vary from OS to OS and CPU to CPU.
Use of the Thread class does avoid the ThreadPool, which is most of the CLR's level of control over thread scheduling, but the OS kernel still decides when threads run. In your case, where each Thread is simply outputting three lines to the console, it's totally expected that one thread would finish before the OS even kicks off the other one.
HOWEVER, you can never guarantee the order in which threads will run. So, if you were to loop this code (with Join() statements) and run it 100 times, you may see several different permutations of "threadA" and "threadB" displayed as the threads are scheduled at different times by the OS. If two EUs are available at EXACTLY the same time there will be significant overlap; if threadA is somehow considered less important than threadB, threadB may execute in its entirety before threadA even begins.