在创建多线程应用程序时,如何确保线程间的协作往往比让线程工作更重要。
线程间的协作最简单的方式是采用Join来进行,如下:
/// <summary>
/// 多线程协作-Join方式
/// 解决线程间同步工作问题
/// </summary>
private static void MultiThreadSynergicWithJoin()
{
int[] array = new int[3];
Thread producer = null, customer = null;
producer = new Thread(() =>
{
Console.WriteLine(String.Format("{0} start work", Thread.CurrentThread.Name));
Random random = new Random();
try
{
array[0] = random.Next(10);
array[1] = random.Next(10);
array[2] = random.Next(10);
Console.WriteLine(String.Format("{0} work over", Thread.CurrentThread.Name));
Thread.Sleep(1000);
}
catch (ThreadAbortException ex)
{
Console.WriteLine(String.Format("Sub Thread {0} Abort", Thread.CurrentThread.Name));
}
})
{
Name = "producer"
};
customer = new Thread(() =>
{
Console.WriteLine(String.Format("{0} start work", Thread.CurrentThread.Name));
try
{
producer.Join();
Console.WriteLine(array[0]);
Console.WriteLine(array[1]);
Console.WriteLine(array[2]);
Console.WriteLine(String.Format("{0} work over", Thread.CurrentThread.Name));
}
catch (ThreadInterruptedException ex)
{
Console.WriteLine(String.Format("Sub Thread {0} Interrupted", Thread.CurrentThread.Name));
}
})
{
Name = "customer"
};
Console.WriteLine("Main Thread");
customer.Start();
producer.Start();
Console.WriteLine("Main Thread Wait Sub Thread");
}
说明:
1、在调用producer.Join()时,customer线程将暂停执行而进入等待producer线程执行的过程。在producer线程执行完毕后,customer线程才返回继续执行后续代码。
2、producer与customer谁先启动无所谓,但应保证在调用producer.Join时满足:producer线程必须启动过,即调用过Start方法,如果在调用Join时,被调用线程已经结束或终止,Join方法将立即返回执行后续代码
3、对于多线程间的协作Join方式较为适合线程数量不多,对资源需求有明确先后顺序的情况(个人总结,如有错误,欢迎拍砖)。