您的位置:首页 > 其它

多线程学习Demo注解(1)

2013-08-29 22:05 225 查看
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();
            }
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: