初学C#线程二

using System;
using System.Threading;


namespace threading
{

    public class Alpha
    {
        public void Beta()
        {
            while (true)
            {
                Console.WriteLine("Alpha.Beta is running in its own thread.");
            }
        }
    }

    public class Simple
    {
        public static int Main()
        {
            Console.WriteLine("Thread Start/Stop/JoinSample");
            Alpha oAlpha = new Alpha();

            Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
            oThread.Start();
            //oThread.Join(2);
            //oThread.Abort();
            while (!oThread.IsAlive)
               Thread.Sleep(4);
            Thread.Sleep(3);//如果没有这句,oThread没有办法运行处结果,因为线程结束太快
             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();
            }
            Console.ReadLine();
            return 0;


        }
    }
}

程序包含Alpha和Simple两个类,在创建线程oThread时指向Alpha.Beta()方法的初始化了ThreadStart代理(delegate)对象,当我们创建的线程oTread调用oThread.Start()方法启动时,实际上程序运行的是Alpha.Beta():

Alpha oAlpha = new Alpha();

Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));

oThread.Start();

所用的线程都是依附于Main()函数所在的线程,Main()函数是C#程序的入口,起始线程称为主线程。如果所有的前台线程都停止了,那么主线程可以终止,而所有的后台线程都将无条件终止。所有的线程虽然在微观上是串行执行的,但是在宏观上可以认为他们是并行执行。

Thread.ThreadState属性

这个属性代表了线程运行时状态,在不同的情况下有不同的值,我们有时候可以通过对该值的判断来设计程序流程。

ThreadState属性的取值如下:

Aborted:线程已停止;

AbortRequested:线程的Thread.Abort()方法已被调用,但是线程还未停止;

Backgound:线程在后台执行,与属性Thread.IsBackground有关;

(后台线程跟前台线程只有一个区别,那就是后台线程不妨碍程序的终止。一旦一个进程所有的前台线程都终止后,CLR(通用语言运行环境)将通过调用任意一个存活中的后台进程的Abort()方法来彻底终止进程。)

Running:线程正在运行;

Stopped:线程已经被停止;

StopRequested:线程正在被要求停止;

Suspended:线程已经被挂起(此状态下,可以通过调用Resume()方法重新运行);

SuspendRequested:线程正在要求被挂起,但是未来得及响应;

Unstarted:未调用Thread.Start()开始线程运行。

WaitSleepJoin:线程因为调用了Wait(),Sleep(),Join()等方法处于封锁状态;

线程之前争夺CPU时间时,CPU是按照线程优先级给予服务。C#提供5个优先级 分别为Highest\Abovenormal\Normal\BelowNormal\Lowest  默认为中间Treahpriority. Normal

原文地址:https://www.cnblogs.com/jingfuluo/p/2985760.html