首页 > 编程语言 > 详细

2021-7-28 多线程的基本练习

时间:2021-07-28 18:35:29      阅读:8      评论:0      收藏:0      [点我收藏+]

多线程

技术分享图片
using System;
using System.Threading;

namespace ThreadTest
{
    class Program
    {
        static void Main(string[] args)
        {
            
            Thread th = Thread.CurrentThread;
            th.Name = "主线程";
            Console.WriteLine(th.Name);
            Thread child = new Thread(ChildThread);
            child.Start();
            Console.WriteLine("子线程正在休眠中");//当前线程继续执行

            ThreadStart childref = new ThreadStart(NumberThread);
            Thread number = new Thread(childref);
            number.Start();
            Thread.Sleep(2000);
            //number.Abort();//线程终止,netcore3.1不能使用终止线程
            number.Interrupt();//中断线程
            Thread.Sleep(2000);
            Console.WriteLine(number.ThreadState);//获取中断线程状态
            Console.ReadKey();
        }
        static void ChildThread()
        {
            var sleepTime = 5000;
            Console.WriteLine("子线程1休眠" + sleepTime / 1000 + "");
            Thread.Sleep(sleepTime);//线程休眠5秒
            Console.WriteLine("子线程1休息完毕");
        }
        static void NumberThread()
        {
            try
            {
                for (int i = 0; i < 10; i++)
                {
                    Thread.Sleep(500);
                    Console.WriteLine(i);
                }
            }
            catch (ThreadInterruptedException e)
            {

                Console.WriteLine("线程已被中止");
            }
            finally
            {
                Console.WriteLine("未找到问题");
            }
        }
    }
}
View Code

 

2021-7-28 多线程的基本练习

原文:https://www.cnblogs.com/WH5212/p/15070386.html

(0)
(0)
   
举报
评论 一句话评论(0
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!