1. Thread 调用线程
Thread thread = new Thread(Run1);
Thread thread2 = new Thread(Run2);
thread.Start();
thread2.Start();
2. ThreadPool 调用线程池
ThreadPool.QueueUserWorkItem(m => {Run1();});
ThreadPool.QueueUserWorkItem(m => {Run2();});
3. Task 调用线程或线程池,比前两个优化了
Task t = new Task(Run1);
Task t2 = new Task(Run2);
t.Start();
t2.Start();
4. Task.Factory 调用任务工厂
Task.Factory.StartNew(Run1);
Task.Factory.StartNew(Run2);
5. Parallel.Invoke 并行任务,这里是先执行Run1和Run2()再执行主线程,和之前四种不一样
Parallel.Invoke(Run1,Run2);
Run1和Run2方法如下,在主线程也可以打印以下看看线程ID是不同的
public void Run1()
{
Thread.Sleep(5000);
Console.WriteLine("调用工作线程1,ThreadID:{0}", Thread.CurrentThread.ManagedThreadId);
}
public void Run2()
{
Thread.Sleep(2000);
Console.WriteLine("调用工作线程2,ThreadID:{0}", Thread.CurrentThread.ManagedThreadId);
}