【后端】C#线程的基础用法

先上效果图:

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

namespace GoldRootManage20230505
{
    internal class Program
    {
        public static int count = 0;
        public static System.Timers.Timer timer;
        public static void Main(string[] args)
        {
            // 定义俩条子线程
            Thread thread1 = new Thread(Run1);
            Thread thread2 = new Thread(Run2);
            // 开始线程
            thread1.Start();
            thread2.Start();
            // 主线程结束时不关闭控制台
            Console.WriteLine("我也不知道我是多少号线程了");
            Console.ReadLine();
        }

        // 线程1
        public static void Run1()
        {
            // 使用全局定时器,不手动stop就无限执行
            timer = new System.Timers.Timer(1000);
            // Run11是定时执行方法
            timer.Elapsed += new System.Timers.ElapsedEventHandler(Run11);
            // 是否无限执行
            timer.AutoReset = true;
            // 是否开启
            timer.Enabled = true;
        }
        public static void Run11(object source, System.Timers.ElapsedEventArgs e)
        {
            count++;
            if (count == 5)
            {
                // 关闭并释放定时器
                timer.Stop();
                timer.Dispose();
            }
            Console.WriteLine("我也有可能是三号线程");
        }

        //线程2
        public static void Run2()
        {
            Console.WriteLine("我是二号线程");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值