线程9:线程的优先级和状态

线程的执行没有规律,如果多个线程执行,能不能设置优先顺序?

线程的优先级可以影响线程的调用顺序,我们可以通过使用Priority枚举属性来设置线程的优先级。

说明:

Highest:    最高级别优先

AboveNormal Highest级别后,在Normal之前。

Normal:   默认情况下最初为Normal

BelowNormal Normal之后,在lowest之前

Lowest BelowNormal之后,最低

线程的状态控制:

Start()  开始

Abort() 中止

Sleep()  休眠

Join()  阻塞

源代码:

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


namespace 线程的优先级和状态控制
{
    class Program
    {
        /// <summary>
        /// 演示线程的优先级
        /// </summary>
        public void Test1()
        {
            Thread t1 = new Thread(Thread1);
            Thread t2 = new Thread(Thread2);
            Thread t3 = new Thread(Thread3);
            Thread t4 = new Thread(Thread4);
            t1.Start();
            t2.Start();
            t3.Start();
            t4.Start();


            //线程的优先级控制
            t4.Priority = ThreadPriority.Highest;
            t3.Priority = ThreadPriority.AboveNormal;
            t2.Priority = ThreadPriority.Normal;
            t1.Priority = ThreadPriority.Lowest;


        }


        /// <summary>
        /// 线程的状态控制
        /// </summary>
        public void Test2()
        {
            Console.WriteLine("你好");
            Thread t1 = new Thread(Thread1);
            Thread t2 = new Thread(Thread2);
            t1.Start();
            t1.Join();
            t2.Start();
          


        }
        public void Thread1()
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(1000);
                 Console.WriteLine("我是线程1");
            }
        }
        public void Thread2()
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(500);
                Console.WriteLine("我是线程2");
            }


        }
        public void Thread3()
        {
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine("我是线程3");
            }
        }
        public void Thread4()
        {
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine("我是线程4");
            }


        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            //obj.Test1();
            obj.Test2();
            Console.ReadLine();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值