zoukankan      html  css  js  c++  java
  • 学习笔记线程的几个常用方法实例

    网上找到的一段代码,经过自己的些微修改,方便理解线程中常用的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();
            }
        }

  • 相关阅读:
    Java面试题(转)
    哪种方式更适合在React中获取数据?
    vue学习之深入响应式原理
    还不会用FindBugs?你的代码质量很可能令人堪忧
    几道大数据面试题(转)
    【Medium翻译】Java抽象类有什么用?
    深入理解Kafka必知必会(上)
    (八十六)c#Winform自定义控件-表格优化(转载)
    IDEA 配置及常用快捷键
    Markdown 复杂公式&常用符号
  • 原文地址:https://www.cnblogs.com/maomaokuaile/p/2827533.html
Copyright © 2011-2022 走看看