using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace 线程池判断结束综合演示
{
class Program
{
public static int iCount = 0;
public static int MaxCount = 10;//允许线程池中运行最多10个线程
static ManualResetEvent eventX = new ManualResetEvent(false); //新建ManualResetEvent对象并且初始化为无信号状态
static void Main(string[] args)
{
Console.WriteLine("ManualResetEvent初始为无信号状态 ");
Console.WriteLine("线程池最大值为 {0} 个线程。", MaxCount);
for (int iItem = 1; iItem <= MaxCount; iItem++)
{
//插入队列元素
Console.WriteLine("加入线程 {0}", iItem);
ThreadPool.QueueUserWorkItem(new WaitCallback(fun1), (object)iItem);
}
Console.WriteLine("等待线程池完成操作。。。"); //等待事件的完成,即线程调用ManualResetEvent.Set()方法
eventX.WaitOne(Timeout.Infinite, true); //WaitOne()方法使调用它的线程等待直到eventX.Set()方法被调用
Console.WriteLine("线程池结束!");
Console.ReadLine();
}
public static void fun1(object j)
{
Console.WriteLine(" {0} {1} :", Thread.CurrentThread.GetHashCode(), j.ToString());
Thread.Sleep(1000);
Interlocked.Increment(ref iCount);
if (iCount == MaxCount)
{
Console.WriteLine();
Console.WriteLine("设置ManualResetEvent为有信号状态,Setting eventX ");
eventX.Set();
}
}
}
}