1、Thread.join()
使用此方法先阻塞调用Thread的线程,确保线程Thread正常终止。
如果线程不终止,则调用方将无限期阻塞。如果调用 Join 时该线程已终止,此方法将立即返回。
此方法更改调用线程的状态以包括 ThreadState..::.WaitSleepJoin。对处于 ThreadState..::.Unstarted 状态的线程不能调用 Join。
案例代码分析:
普通线程的创建,通过 委托ThreadStart对应的函数来执行相关操作;
通过线程池,可以直接从池中查找出空闲线程,让它执行委托WaitCallback对应函数来执行相关操作。使用时要与AutoResetEvent来并用,以在线程结束时通知主线程退出;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace joinDemo
- {
- class Program
- {
- static void Main()
- {
- /* 通知正在等待的线程已经发生事件 */
- AutoResetEvent autoEvent = new AutoResetEvent(false);
- Thread regularThread =
- new Thread(new ThreadStart(ThreadMethod));
- regularThread.Start();
- /*
- * 提供一个线程池,该线程池可用于发送工作项、处理异步 I/O、
- * 代表其他线程等待以及处理计时器。
- */
- ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod),
- autoEvent);
- /* Wait for foreground thread to end. 一直阻塞 */
- regularThread.Join();
- /* Wait for background thread to end. 主线程使用WaitOne来等待解除线程 */
- autoEvent.WaitOne();
- Console.ReadLine();
- }
- static void ThreadMethod()
- {
- Console.WriteLine("ThreadOne, executing ThreadMethod, " +
- "is {0}from the thread pool.",
- Thread.CurrentThread.IsThreadPoolThread ? "" : "not ");
- }
- static void WorkMethod(object stateInfo)
- {
- Console.WriteLine("ThreadTwo, executing WorkMethod, " +
- "is {0}from the thread pool.",
- Thread.CurrentThread.IsThreadPoolThread ? "" : "not ");
- /* Signal that this thread is finished.事件通知,解除线程阻塞 */
- ((AutoResetEvent)stateInfo).Set();
- }
- }
- }
2、ThreadPool类
ThreadPool类提供一个线程池,该线程池可用于发送工作项、处理异步 I/O、代表其他线程等待以及处理计时器。
案例分析:
在本案例中,使用线程池来找到一个线程执行函数,实质减少了new thread等过程。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace ThreadPoolDemo
- {
- class Program
- {
- static void Main(string[] args)
- {
- // Queue the task.
- /* 请求线程池中的空闲一个线程来处理工作项 */
- ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
- Console.WriteLine("Main thread does some work, then sleeps.");
- /*
- * If you comment out(注释掉) the Sleep, the main thread exits before
- * the thread pool task runs. The thread pool uses background
- * threads, which do not keep the application running,即main主线程退出后,
- * 其它线程不会再执行. (This
- * is a simple example of a race condition.)
- */
- Thread.Sleep(1000);
- Console.WriteLine("Main thread exits.");
- Console.ReadLine();
- }
- ///
- /// This thread procedure performs the task.
- ///
- ///
- static void ThreadProc(Object stateInfo)
- {
- /*
- *
- * No state object was passed to QueueUserWorkItem, so
- * stateInfo is null.
- */
- Console.WriteLine("Hello from the thread pool.");
- }
- }
- }