C#线程初步

举报
tea_year 发表于 2021/12/22 23:22:56 2021/12/22
【摘要】 1.定义类A 用于循环执行的方法 using System; using System.Collections.Generic; using System.Linq; using System.Tex...

1.定义类A

用于循环执行的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class A
    {
        public void fun() {
            while (true) {
                Console.WriteLine("工作线程:正在执行A.fun方法...");
            }
        }
    }
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

2.主程序进行测试

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("主线程启动..");
            A a = new A();  //创建A的实例;

            Thread t1 = new Thread(new ThreadStart(a.fun)); 
            //创建一个线程,使之执行A类的fun()方法

            Console.WriteLine("启动主线程...");
            t1.Start();

            while (!t1.IsAlive) ;//循环,直到工作线程激活;

            Console.WriteLine("主线程休眠1ms...");
            Thread.Sleep(1);        //让主线程休眠1ms,以允许工作线程完成自己的工作;

            Console.WriteLine("终止工作线程");
            t1.Abort();

            //Console.WriteLine("阻塞工作线程");
            //t1.Join();

            try
            {
                Console.WriteLine("试图重新启动工作线程");
                t1.Start();
            }
            catch (Exception)
            {
                Console.WriteLine("终止后的线程不能重启,在重启时引发相关异常");
            }

            Console.WriteLine("主线程结束");
            

        }
    }
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

3.分别测试

3.1 终止线程

在这里插入图片描述

3.2 阻塞线程

在这里插入图片描述

通过比较会发现阻塞之后不再进入到主程序,不再重启!

文章来源: aaaedu.blog.csdn.net,作者:tea_year,版权归原作者所有,如需转载,请联系作者。

原文链接:aaaedu.blog.csdn.net/article/details/109102187

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。