线程是进程中某个单一顺序的控制流,是程序运行中的调度单位,是程序执行流的最小单位,一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成。 线程本身不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的所有资源。 线程也有就绪、阻塞和运行三种基本状态。每个程序都至少有一个线程,若程序只有一个线程,那就是程序进程自己。html
class Fish { public string Name { get; set; } public Fish() { Name = "小黄鱼" ; } public void Move() { Console.WriteLine(string .Format("{0}在游来游去......", Name)); } } class Program { static void Main(string[] args) { Fish fish = new Fish(); Thread t1 = new Thread(() => { fish.Move(); }); t1.IsBackground = true; t1.Start(); Fish fish2 = new Fish() { Name = "大鲨鱼" }; Thread t2 = new Thread(() => { fish2.Move(); }); t2.IsBackground = true; t2.Start(); Console.ReadKey(); } }
static void Main(string[] args) { Fish fish = new Fish(); Fish fish2 = new Fish() { Name = "大鲨鱼" }; Fish fish3 = new Fish() { Name = "灯笼鱼" }; Fish fish4 = new Fish() { Name = "红鲤鱼" }; Fish fish100 = new Fish() { Name = "灯笼鱼" }; ThreadPool.QueueUserWorkItem(f => { fish.Move(); }); ThreadPool.QueueUserWorkItem(f => { fish2.Move(); }); ThreadPool.QueueUserWorkItem(f => { fish3.Move(); }); ThreadPool.QueueUserWorkItem(f => { fish4.Move(); }); ThreadPool.QueueUserWorkItem(f => { fish100.Move(); }); Console.ReadKey(); }
运行后屏幕以下:多线程
class Program { static void Main(string[] args) { //用来取消小黄鱼线程 CancellationTokenSource cts = new CancellationTokenSource (); Fish fish = new Fish(); Fish fish2 = new Fish() { Name = "大鲨鱼" , Score =100 }; Task t1 = new Task(() => fish.Move(cts.Token), cts.Token); t1.Start(); //小黄鱼被击中后显示积分 t1.ContinueWith(fish.ShowScore); Task t2 = new Task(() =>fish2.Move(cts.Token), cts.Token); t2.Start(); //大鲨鱼鱼被击中后显示积分 t2.ContinueWith(fish2.ShowScore); //按任意键发射 Console.ReadKey(); //武器工厂线程池,执行一组任务 Gun gun = new Gun(); LaserGun laserGun = new LaserGun(); TaskFactory taskfactory = new TaskFactory(); Task[] tasks = new Task[] { taskfactory.StartNew(()=>gun.Fire()), taskfactory.StartNew(()=>laserGun.Fire()) }; //执行武器们开火 taskfactory.ContinueWhenAll(tasks, (Task) => { }); //鱼儿们被击中了就会去调显示积分的方法 cts.Cancel(); Console.ReadLine(); } } class Fish { public string Name { get; set; } public int Score { get; set; } public Fish() { Name = "小黄鱼" ; Score = 1; } /// <summary> /// 游动 /// </summary> public void Move(CancellationToken ct) { //若是没有被击中,就一直游阿游,用IsCancellationRequested判断 while (!ct.IsCancellationRequested) { Console.WriteLine(string .Format("{0}在游来游去......", Name)); Thread.Sleep(1000); } } //中枪死亡后显示奖励 public void ShowScore(Task task) { Console.WriteLine(string .Format("{0}中弹了,您获得{1}分......" , Name, Score)); } } abstract class Weapon { public string Name { get; set; } public abstract void Fire(); } class Gun : Weapon { public Gun() : base() { Name = "双射枪" ; } public override void Fire() { Console.WriteLine(string .Format("咻咻咻,{0}向鱼儿们发射子弹......" , Name)); } } class LaserGun : Weapon { public LaserGun() : base() { Name = "激光炮" ; } public override void Fire() { Console.WriteLine(string .Format("嗖嗖嗖,{0}向鱼儿们发射炮弹......" , Name)); } }