• C#多线程的用法3-线程间的协作Join


    在创建多线程应用程序时,如何确保线程间的协作往往比让线程工作更重要。

    线程间的协作最简单的方式是采用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方式较为适合线程数量不多,对资源需求有明确先后顺序的情况(个人总结,如有错误,欢迎拍砖)。

  • 相关阅读:
    visual studio 2013 生成依赖项关系图出错
    redHat 安装mono 错误
    redHat 安装mono 错误
    msdn帮助,离线下载
    w
    msdn帮助,离线下载
    vs2013 找不到帮助 help查看器
    vs2013 找不到帮助 help查看器
    c# wpf 加密文本
    c# wpf 加密文本
  • 原文地址:https://www.cnblogs.com/dw039/p/7398715.html
Copyright © 2020-2023  润新知