一、线程与进程的概念
一个程序就是一个进程,一个线程就是程序程序执行的一个任务,当程序需要执行多个任务就要开启多个线程。
从微观上来说,多个线程不会同时进行,它是在快速的切换进行,看起来就好像多个程序同时进行
在单线程中,程序代码按照调用顺序依次往下执行,如果需要一个进程同时完成多段代码的操作,就需要用到多线程
=================================================================================
二、线程的生命周期
出生状态——就绪状态——运行状态
出生状态:创建了线程,但未调用start之前的状态
就绪状态:调用了start之后,得到系统资源之前
运行状态:得到系统资源之后
运行状态分为:等待、休眠、阻塞、死亡
等待:调用了Suspent之后,调用Resume之前
休眠:在sleep的执行时间里面
阻塞:向用户输出信息,或者等待用户输入的状态
死亡:线程执行完毕
。。。。。。。。。。。。。。。。。。。。。。。。。。。。
start 使线程被安排进行执行(在最开始的时候用)
join 组织调用其他线程,直到本线程结束为止
Suspent 挂起线程
Resume 继续执行已挂起的线程
Sleep 暂停当前线程,时间长度为(指定的毫秒数)
Abort 终止线程
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
示例代码:
static void CountTime()
{
Console.WriteLine("循环完毕~~~");
Console.ReadKey();
}
static void Main(string[] args)
{
Thread threadFirst = new Thread(CountTime);
threadFirst.Start();
threadFirst.Suspend();
threadFirst.Resume();
threadFirst.Abort();
threadFirst.Join();
}
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
使线程1休眠的代码:
static void Main(string[] args)
{
Thread th1 = new Thread(fun1);
Thread th2 = new Thread(fun1);
th1.Name = "线程1"; //给线程命名,方便只有识别
th2.Name = "线程2---------";
th1.Start();
th2.Start();
Console.ReadKey();
}
public static void fun1()
{
if (Thread.CurrentThread.Name == "线程1") //可以通过字段 CurrentThread来获取当前线程,然后就可以判断是哪个线程在进行了
{
Thread.Sleep(20); //睡眠当前线程
}
for (int i = 0; i < 20; i++)
{
Console.WriteLine("这里是线程{0},当前执行{1}次", Thread.CurrentThread.Name, i);
}
}
===============================================================================
三、优先级
优先级分为: AboveNormal BelowNormal Highest Lowest Normal
默认的优先级为Normal
设置方法: 设置方法:thread1.Priority=ThreadPriority.Lowest
=====================================================================
四、线程同步机制
C# 提供线程同步机制防止资源访问的冲突,主要用到 lock关键字、Monitor类、Mutex类
线程同步:某一时刻,只有一个线程可以访问资源
=====================================================================
五、不同参数线程的创建与使用
1、无参数的线程 典型代码:
class Program
{
static void CountTime()
{
DateTime beginTime = DateTime.Now;
for (int i = 0; i < 999999999; i++)
{
}
TimeSpan ts = beginTime.Subtract(DateTime.Now);
Console.WriteLine("循环完毕~~~"+ts.TotalMilliseconds);
Console.ReadKey();
}
static void Main(string[] args)
{
Thread threadFirst = new Thread(CountTime);
threadFirst.Start();
}
}
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
2、一个参数的线程 典型代码:
class Program
{
static void print(object str) //注意参数类型是object型
{
Console.WriteLine(str.ToString());
Console.ReadKey();
}
static void Main(string[] args)
{
Thread threadFirst = new Thread(print);
threadFirst.Start("key");
}
}
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
3、多参数线程 典型代码:
class Program
{
static void ShowName(object li)
{
List<string> list = li as List<string>;
if (list != null)
{
foreach (string s in list)
{
Console.WriteLine(s);
}
}
}
static void Main(string[] args)
{
Thread thread = new Thread(ShowName);
thread.IsBackground = true;
thread.Start(new List<string>() { "刘德华","王力宏","孙燕姿"});
Console.ReadKey();
}
}