线程的执行没有规律,如果多个线程执行,能不能设置优先顺序?
线程的优先级可以影响线程的调用顺序,我们可以通过使用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();
}
}
}