一、线程的开启
1、使用委托开启线程
class Program
{
static int test1(int i)
{
Console.WriteLine("test1");
return i;
}
static void CallBack(IAsyncResult ar)
{
Console.WriteLine("CallBack");
Console.WriteLine(ar.AsyncState);
}
static void Main(string[] args)
{
int b = 100;
int res = 0;
Func<int,int> a = test1;
//BeginInvoke第一个参数是给委托线程的参数,第二个参数是委托结束时的回调函数,第三个是回调函数的传参。
IAsyncResult ar = a.BeginInvoke(3, CallBack,b);
bool isEnd = ar.AsyncWaitHandle.WaitOne(10);//判断线程是否结束,参数是等待时间,单位 ms 。
if (isEnd)
{
res = a.EndInvoke(ar);//取得委托线程结束时的返回值
}
Console.WriteLine("main");
Console.WriteLine(res);
Console.ReadKey();
}
}
2、使用Thread开启线程
static void test1(Object i)//参数类型写Object,使用时按实际传参类型使用即可
{
Console.WriteLine("test1 " + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(i);
}
Thread t = new Thread(test1);
t.Start(b);//b 为test1的参数
/*****************************************************************************************/
class MyThread
{
int I = 0;
string S = "";
public MyThread(int i,string s)
{
I = i;
S = s;
}
public void test2()
{
Console.WriteLine(S + I + " " + Thread.CurrentThread.ManagedThreadId);
}
}
MyThread mt = new MyThread(20,"你好");
Thread MT = new Thread(mt.test2);
MT.Start();//mt。test2的参数在类mt中
Thread的一些属性
IsBackground 设置为true时,在无前台线程时该线程会被强制停止。
Priority 设置为ThreadPriority. 的一个枚举 优先级高的执行 同级别循环调度
Abort() 强行终止线程,会抛出异常
Join() 停止当前线程,等待调用Join的线程完成再继续执行。
3、线程池开启线程,线程池适合许多小任务,线程池中的线程都是后台线程!!!
static void test1(object i)
{
Console.WriteLine("test1 " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(100);
Console.WriteLine(i);
}
ThreadPool.QueueUserWorkItem(test1,1);
4、Task 任务开启线程
static void test1(object i)
{
Console.WriteLine("test1 " + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(100);
Console.WriteLine(i);
}
Task tk = new Task(test1, 1);
tk.Start();
TaskFactory tkf = new TaskFactory();
Task tk_f = tkf.StartNew(test1, 1);
5、ContinueWith
Task tk = new Task(test1, 1);
tk.Start();
Task tk2 = tk.ContinueWith(test1);
6、使用任务创建多线程会有父任务和子任务。父任务完成子任务为完成时父任务的状态是等待子任务完成
二、条件争用
使用 lock(m){
//m必须是引用类型,m被锁定后其他线程无法锁定,m无法锁定时线程原地等待。
}
上锁顺序必须合理,不能出现死锁情况。!!!