多线程(1-6 Thread)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadClass
{
class Program
{
static void Main(string[] args)
{
#region 控制线程
{
//Console.WriteLine("mianThread Start!");
//Thread th = new Thread(newThread);
//th.Start();//将当前实例的状态更改为ThreadState.Running
//Console.WriteLine("newThread State:{0}", th.ThreadState);
//th.Join(); //等待调用此方法的线程结束
//Console.WriteLine("newThread State:{0}", th.ThreadState);
//th.Abort(); //在调用此方法的线程上引发ThreadAbortExcepion, 以开始终止次线程的过程,调用此方法通常会终止线程
//Console.WriteLine("newThread State:{0}", th.ThreadState);
//Console.Read();
}
#endregion
#region Thread类创建线程
//不带参数
Thread th = new Thread(newThread);
th.Start();
//带参数
//有两种方式,一种是使用带ParameterizedThreadStart委托参数的Thread的构造函数,另外一种是定义一个自定义类。
//a: 使用带ParameterizedThreadStart委托参数的Thread的构造函数
Thread th2 = new Thread(Thread_param);
th2.Start(50);
//b: 定义一个自定义类
// 使用自定义类实现带参数的线程
MyThread<string> myThread = new MyThread<string>("Thread_child");
Thread th3 = new Thread(myThread.ThreadChild);
th3.Start();
Console.WriteLine("This is main thread");
Console.Read();
运行结果:
#endregion
#region 后台线程
/*Thread类默认创建的是前台线程,所以我们前面创建的线程全部都是前台线程。
只要有一个前台线程在运行,应用程序的进程就在运行。
如果有多个前台线程在运行,而Main()方法(主线程)结束了,应用程序的进程就仍然是激活的,直到所有前台线程完成其任务为止。
*
*
* 后台线程
* 后台线程和前台线程相反。
* 对于后台线程,当主线程结束后,应用程序的进程就结束终止了,在所有前台线程结束后,后台线程就会被终止;
*
* 可以通过设置Thread类的IsBackground属性来确定该线程是前台线程还是后台线程
*/
#endregion
}
static void newThread()
{
Console.WriteLine("this is child thread");
Console.WriteLine("newThread State!");
Thread.Sleep(1000);
Console.WriteLine("newThread Complete!");
}
static void Thread_param(object msg)
{
Console.WriteLine("this is child thread");
int message = (int)msg;
Console.WriteLine("Result:{0}",message);
}
}
class MyThread<T>
{
private T data;
public MyThread(T data)
{
this.data = data;
}
public void ThreadChild()
{
Console.WriteLine("this is child thread");
Console.WriteLine("Child Thread Start! Result:{0}",data);
}
}
}
图一: