学习笔记线程的几个常用方法实例

网上找到的一段代码,经过自己的些微修改,方便理解线程中常用的sleep,join,abort用法

class Program
    {
        public static void doSomething()
        {
            for (int i = 0; i < 100; i++)
            {

      //当前进程每打印一个数字就等待100毫秒钟
                Console.WriteLine("doSomething thread:{0}.", i);
                Thread.Sleep(100);

      //如果i=50,则当前进程终止
                if (i == 50)
                {
                    Thread.CurrentThread.Abort();
                }
            }
        }

        static void Main(string[] args)
        {
            //thread.sleep,join,abort执行
           //开始主进程

    try
            {
                //Thread.CurrentThread.Abort();//此句当前主进程终止,退出程序
                ThreadStart startThread = new ThreadStart(doSomething);
                Thread newThread = new Thread(startThread);
                newThread.Start();//子进程开始
                for (int i = 0; i < 50; i++)
                {

        //主进程每打印一个数字就等待100毫秒钟
                    Console.WriteLine("mainThread:{0}.", i);
                    Thread.Sleep(100);

        //当i=25的时候,子进程加入到主进程中来,子进程此时输出到25这个数字
                    if (i == 25)
                    {
                        newThread.Join();
                    }

        //主进程等待子进程执行完毕,才会接着向下执行

        //当i=40的时候,主线程终止,此时进入到catch块
                    if (i == 40)
                    {
                        Thread.CurrentThread.Abort();
                    }
                }
            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine("abort thread state:{0}", Thread.CurrentThread.ThreadState.ToString());
                Console.WriteLine("abort message:{0}", e.Message);

      //主进程不终止,继续执行
                Thread.ResetAbort();//如果注释此句,线程将执行完finall后中止
            }
            finally
            {
                Console.WriteLine("finally thread state:{0}", Thread.CurrentThread.ThreadState.ToString());
            }
            Console.WriteLine("thread state:{0}", Thread.CurrentThread.ThreadState.ToString());

            Console.ReadLine();
        }
    }

原文地址:https://www.cnblogs.com/maomaokuaile/p/2827533.html