Reprinted URL: http://www.cnblogs.com/slikyn/articles/1525940.html
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.
For specific code, the console application is used as an example: The program test.exe starts to run 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 is executed. 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
{
Class testthread
{
Private Static void threadfuncone ()
{
For (INT I = 0; I <10; I ++)
{
Console. writeline (thread. currentthread. Name + "I =" + I );
}
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 ();
}
}
}
The test result is as follows:
Conclusion: from the test, we can clearly see that mainthread is blocked after newthread. Join is called until newthread
After the execution is completed, the execution continues.