多线程学习Demo注解(1)

Thread.Join() 的解释:点击打开链接

using System;
using System.Threading;

namespace ThreadTest
{
    public class Alpha
    {
        public void Beta()
        {
            while (true)
            {
                Console.WriteLine("当前线程:{0}", Thread.CurrentThread.Name);
                Console.WriteLine("子线程在作死地跑跑跑!");
            }
        }
    };

    public class Simple
    {
        public static void Main()
        {
            Thread.CurrentThread.Name = "主线程";
            Console.WriteLine("Thread Start/Stop/Join Sample");

            Alpha oAlpha = new Alpha();
            //这里创建一个线程,使之执行Alpha类的Beta()方法
            Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
            oThread.Name = "子线程";
            oThread.Start();
            //当子线程不在执行状态则一直不跳出循环——>等待子线程进入执行状态
            while (!oThread.IsAlive) ;
            Console.WriteLine("当前线程:{0}, 睡眠一会!", Thread.CurrentThread.Name);
            //再等待2毫秒, 让子线程有点时间做一下自己的事情
            Thread.Sleep(2);
            Console.WriteLine("当前线程:{0}, 即将要中止子线程!", Thread.CurrentThread.Name);
            oThread.Abort();
            //此处不太明白
            oThread.Join();
            //子线程阻止主线程, 直到子线程完成自己的工作? 似乎没有太大意义
            Console.WriteLine();
            Console.WriteLine("Alpha.Beta has finished");
            try
            {
                Console.WriteLine("Try to restart the Alpha.Beta thread");
                //已中止的线程无法再启动!
                oThread.Start();
            }
            catch (ThreadStateException)
            {
                Console.Write("ThreadStateException trying to restart Alpha.Beta. ");
                Console.WriteLine("Expected since aborted threads cannot be restarted.");
                Console.ReadLine();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值