标签:
实现思路:线程执行后进行阻塞,判断当前标记是否达到设置的并发数,如果未达到上限,执行队列中将继续增加线程;如已达到其余线程排队等候。
实例代码:
注:其中用到Mutex与Interlocked两个与线程相关的类,需要加上 using System.Threading; 引用Threading命名空间。
public class MutexTest
{
private static int poolFlag = 0; //声明标记
private const int amountThread = 10;//线程总量
private const int maxThread = 3;//可执行线程最大数量
private static Mutex muxConsole = new Mutex();
public static void Main()
{
for (int i = 0; i < amountThread; i++)
{
// 创建指定数量的线程,线程调用Run函数
Thread trd = new Thread(new ThreadStart(Run));
trd.Name = "线程" + i;
trd.Start();
}
}
public static void Run()
{
muxConsole.WaitOne(); //阻塞队列
Interlocked.Increment(ref poolFlag); //标记+1
if (poolFlag < maxThread) //判断是否达到线程上限
muxConsole.ReleaseMutex(); //释放队列锁,加入执行线程
Console.WriteLine("{0} 正在运行......\n", Thread.CurrentThread.Name);
Thread.Sleep(3000); //模拟执行,暂停3秒钟
Console.WriteLine("{0} 已经中止......\n", Thread.CurrentThread.Name);
Interlocked.Decrement(ref poolFlag); //标记-1
try
{
muxConsole.ReleaseMutex(); //释放阻塞
}
catch { }
}
}
标签:
原文地址:http://www.cnblogs.com/icejd/p/4354023.html