多线程技术应用(一)
DYT_JCBK(1/900:2018/9/16)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadTest
{
class Program
{
static void Main(string[] args)
{
\#region 1.无参的调用方法
//Thread thread1 = new Thread(new ThreadStart(Thread1));//创建无参的线程
//thread1.Start();//调用start方法执行线程
//Console.ReadKey();
\#endregion
\#region 2.通过匿名委托或lambda表达式来为Thread构造方法赋值
//Thread thread1 = new Thread(delegate () \{ Console.WriteLine("匿名委托建立线程"); \});
//thread1.Start();
//Thread thread2 = new Thread(() => Console.WriteLine("我是通过Lambda表达式创建的委托"));
//thread2.Start();
//Console.ReadKey();
\#endregion
\#region 3.ParameterizedThreadStart是一个有参的,返回值为void的委托,委托参数的类型必须是Object的
//Thread thread = new Thread(new ParameterizedThreadStart(Thread1));
//thread.Start("这是一个有参数的委托");
//Console.ReadKey();
\#endregion
\#region 4.线程的常用方法
/\*
Abort() 终止线程;
GetDomain() 返回当前线程正在其中运行的当前域
GetDomainId() 返回当前线程正在其中运行的当前域ID
Join() 已重载.阻塞调用线程,直到某个线程终止时为止
Interrupt() 中断处于WaitSleepJoin终止时为止
Resume() 继续运行已经挂起的线程
Start() 执行本线程
Suspend() 挂起当前线程,如果当前线程处于已经挂起的状态则不起作用
Sleep() 把正在执行的线程挂起一段时间
\*/
\#endregion
\#region 5.Thread的方法练习
获取正在运行的线程
//Thread thread = Thread.CurrentThread;
设置线程的名字
//thread.Name = "Main Thread";
获取当前线程的唯一标识符
//int id = thread.ManagedThreadId;
获取当前线程的状态
//ThreadState state = thread.ThreadState;
//ThreadPriority priority = thread.Priority;
//string msg = string.Format("Thread ID:\{0\}\\n" + "Thread Name:\{1\}\\n" + "Thread State:\{2\}\\n" + "Thread Priority:\{3\}\\n", id, thread.Name, state, priority);
//Console.WriteLine(msg);
//Console.ReadKey();
\#endregion
\#region 6.前台线程和后台线程
/\*\*
\* 前台线程:只有所有的前台线程都结束,应用程序才能结束,默认情况下创建的线程都是前台线程
\* 后台线程:只要所有的前台线程结束,后台线程自动结束,通过Thread>IsBackground设置后台线程,必须在start()方法之前设置线程类型,因为一旦运行,无法
\* 改变类型
\* /\*/
//演示先后台线程
BackGroundTest backGround = new BackGroundTest(10);
//创建前台线程
Thread fthread = new Thread(new ThreadStart(backGround.RunLoop));
//给线程命名
fthread.Name = "前台线程";
BackGroundTest backGround1 = new BackGroundTest(20);
//创建后台线程
Thread bthread = new Thread(new ThreadStart(backGround1.RunLoop));
bthread.Name = "后台线程";
//设置为后台线程
bthread.IsBackground = true;
//启动线程
fthread.Start();
bthread.Start();
\#endregion
\}
\#region 1.无参的调用方法
//public static void Thread1()
//\{
// Console.WriteLine("这是无参的方法");
//\}
\#endregion
\#region 3.ParameterizedThreadStart是一个有参的,返回值为void的委托
//public static void Thread1(Object obj)
//\{
// Console.WriteLine(obj);
//\}
\#endregion
\}
\#region 6.前台线程和后台线程
class BackGroundTest
\{
private int count;
public BackGroundTest(int count)
\{
this.count = count;
\}
public void RunLoop()
\{
//获取当前线程的名称
string threadName = Thread.CurrentThread.Name;
for (int i = 0; i < count; i++)
\{
Console.WriteLine("\{0\}计数:\{1\}", threadName, i.ToString());
//线程休眠500ms
Thread.Sleep(500);
\}
Console.WriteLine("\{0\}完成计数", threadName);
\}
\}
\#endregion
}
还没有评论,来说两句吧...