Thread. Join () in C #
Today is the first time I have come into contact with thread in C #. I have studied the thread. Join () method, and I will talk about my understanding below.
The explanation of thread. Join () in msdn is vague: blocks the calling thread until a thread terminates
There are two main problems: 1. What is the calling thread?
2. What is a thread?
First, let's take a look at the related concepts: When we execute an .exe file, we actually start a process and start at least one thread at the same time,
But the real work is the thread, just like a team with several people, but the real work is not the team.
SpecificCodeTake console application as an example:ProgramTest.exe runs from the main function. In fact, there is a thread.
When executing the main function, we call it mainthread. If we declare a thread in the main function, it is called newthread and
Newthread. Start () method, when mainthread encounters newthread. Start () when processing the code in the main function, it will
Call newthread.
Based on the above discussion, we can draw a conclusion: In our example, the calling thread is mainthread, while a thread
It refers to the newthread thread called by mainthread.
Now back to the msdn explanation, we can translate:When newthread calls the join method, mainthread is stopped,
Until the newthread thread execution is complete .In this way, I understand O (∩ _ ∩) O Haha ~
Now, the analysis is complete. Let's take a look at the test cases:
Title
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. Threading;
namespace test
{< br> class testthread
{< br> Private Static void threadfuncone ()
{< br> for (INT I = 0; I <10; I ++)
{< br> console. writeline (thread. currentthread. name + "I =" + I);
}< br> console. writeline (thread. currentthread. name + "has finished");
}
Static void main (string [] ARGs)
{
Thread. currentthread. Name = "mainthread ";
Thread newthread = new thread (New threadstart (testthread. threadfuncone ));
Newthread. Name = "newthread ";
For (Int J = 0; j <20; j ++)
{
If (j = 10)
{
Newthread. Start ();
Newthread. Join ();
}
Else
{
Console. writeline (thread. currentthread. Name + "J =" + J );
}
}
Console. Read ();
}
}
}