代码:[C#] 纯文本查看 复制代码 public class MutexTest
{
private static int poolFlag = 0;//标记
private const int amountThread = 100;//线程总量
private const int maxThread = 10;//可执行线程最大数量
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(5000); //模拟执行
Console.WriteLine("{0} 已经中止......\n", Thread.CurrentThread.Name);
//标记-1
Interlocked.Decrement(ref poolFlag);
}
}
问题:
备注:
如果有更好的多线程并发队列,希望分享 |