多线程就是多个线程同时工作的过程,我们可以将线程看作是程序的执行路径,每个线程都定义了一个独特的控制流,用来完成特定的任务。如果你的应用程序涉及到复杂且耗时的操作,那么使用多线程来执行是非常有益的。使用多线程可以节省CPU资源,同时提高应用程序的执行效率,例如现代操作系统对编程的视线就用到了多线程。到目前为止我们编写的示例程序都是单线程的应用程序,这样的应用程序一次只能执行一个任务。
一、线程的生命周期
线程生命周期开始于我们创建System.Threading.Thread类对象的时候,当线程被终止或完成执行时生命周期终止。
下面列出了线程生命周期中的各种状态:
1.未启动状态:当线程实例被创建但Start方法为被调用时的状况;
2.就绪状态:当线程准备好运行并等待CPU周期时的状况;
3.不可运行状态:下面几种情况下线程是不可运行的:
- 已经调用Sleep方法;
- 已经调用Wait方法;
- 通过I/O操作阻塞。
4.死亡状态:当线程已完成执行或已中止时的状况。
二、主线程
在C#中,System.Threading.Thread类用于处理线程,它允许在多线程应用程序中创建和访问各个线程。在多线程执行的第一个线程称为主线程,当C#程序开始执行时,将自动创建主线程,而使用Thread类创建的线程则称为子线程,你可以使用Thread类的CurrentThread属性访问线程。下面通过示例程序演示主线程的执行:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace _054
{
internal class Program
{
static void Main(string[] args)
{
Thread th = Thread.CurrentThread;
th.Name = "主线程";
Console.WriteLine("这是:{0}",th.Name);
Console.ReadKey();
}
}
}
二、Thread类中的属性和方法
三、创建线程
C#是通过扩展Thread类来创建线程的,然后使用扩展的Thread类调用Start()方法开始执行子线程。示例代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace _054
{
internal class Program
{
public static void CallToChildThread()
{
Console.WriteLine("执行子线程");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("在Main函数中创建子线程");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
四、管理线程
Threa类提供了各种管理线程的方法,比如可以使用sleep()方法使线程在特定时间段暂停,示例如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace _055
{
internal class Program
{
public static void CallToChildThrea()
{
Console.WriteLine("执行子线程");
//线程暂停5000毫秒
int sleepfor = 5000;
Console.WriteLine("子线程暂停{0}秒",sleepfor/1000);
Thread.Sleep(sleepfor);
Console.WriteLine("继续执行子线程");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThrea);
Console.WriteLine("在Main函数中创建子线程");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
标签:Console,Thread,C#,System,线程,using,五十六,多线程 From: https://www.cnblogs.com/daihaoliulingyi601/p/17956949