Thread.Join()方法,顾名思义,在一个线程中加入一些东西。
MSDN上解释其作用为:阻塞 “调用线程” 直到某个线程结束。
这个翻译过来的解释有点晦涩。举个例子如下:
static void Main()
{
Thread t=new Thread(new ThreadStart(ThreadMethod));
t.Start();
t.Join();
Console.WriteLine("I am Main Thread");
Console.Read();
}
void ThreadMethod()
{
...
}
从上面的代码中,我们可以看到存在两个线程:主线程和线程t
回到Join,这里所说的调用方就是主线程,主线程调用线程t的Join方法,导致主线程阻塞,直到t线程执行完毕,才返回到主线程中。
简单理解,在主线程中调用t.Join(),也就是在主线程中加入了t线程的代码,必须让t线程执行完毕之后,主线程(调用方)才能正常执行。
代码示例:
代码
staticvoid Main(string[] args)
{
// AutoResetEvent autoEvent = new AutoResetEvent(false);
Thread regularThread =new Thread(new ThreadStart(ThreadMethod));
regularThread.Start();
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod1),regularThread);
Console.WriteLine("i am main thread!");
// regularThread.Join();
Console.WriteLine("i am main thread!");
// autoEvent.WaitOne();
Console.Read();
}
staticvoid ThreadMethod()
{
for (int i =0; i <5; i++)
{
Console.WriteLine("ThreadOne 第 {0} 次执行,executing ThreadMethod,is {1} from the thread pool.",i+1, Thread.CurrentThread.IsThreadPoolThread ?"" : "not");
Thread.Sleep(1000);
}
}
staticvoid WorkMethod1(object stateInfo)
{
Console.WriteLine("ThreadTwo,executing WorkMethod,is {0} form the thread pool.", Thread.CurrentThread.IsThreadPoolThread ?"" : "not");
// ((AutoResetEvent)stateInfo).Set();
((Thread)stateInfo).Join();
for (int i =0; i <5; i++)
{
Console.WriteLine("ThreadTwo 第 {0}次执行,executing WorkMethod,is {1} form the thread pool.",i+1, Thread.CurrentThread.IsThreadPoolThread ?"" : "not");
}
}
{
// AutoResetEvent autoEvent = new AutoResetEvent(false);
Thread regularThread =new Thread(new ThreadStart(ThreadMethod));
regularThread.Start();
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod1),regularThread);
Console.WriteLine("i am main thread!");
// regularThread.Join();
Console.WriteLine("i am main thread!");
// autoEvent.WaitOne();
Console.Read();
}
staticvoid ThreadMethod()
{
for (int i =0; i <5; i++)
{
Console.WriteLine("ThreadOne 第 {0} 次执行,executing ThreadMethod,is {1} from the thread pool.",i+1, Thread.CurrentThread.IsThreadPoolThread ?"" : "not");
Thread.Sleep(1000);
}
}
staticvoid WorkMethod1(object stateInfo)
{
Console.WriteLine("ThreadTwo,executing WorkMethod,is {0} form the thread pool.", Thread.CurrentThread.IsThreadPoolThread ?"" : "not");
// ((AutoResetEvent)stateInfo).Set();
((Thread)stateInfo).Join();
for (int i =0; i <5; i++)
{
Console.WriteLine("ThreadTwo 第 {0}次执行,executing WorkMethod,is {1} form the thread pool.",i+1, Thread.CurrentThread.IsThreadPoolThread ?"" : "not");
}
}
代码中,存在三个线程:主线程、regularThread和线程池中的一个线程。在线程池中的线程中调用了regularThread.Join()方法;
执行结果:
可以看到线程池中线程循环中的内容在regularThread的内容执行完毕之后才执行。