• C#线程并发执行的实例[转]


    实现思路:线程执行后进行阻塞,判断当前标记是否达到设置的并发数,如果未达到上限,执行队列中将继续增加线程;如已达到其余线程排队等候。
    实例代码:

    注:其中用到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} 正在运行......
    ", Thread.CurrentThread.Name);
                 Thread.Sleep(3000);   //模拟执行,暂停3秒钟
                 Console.WriteLine("{0} 已经中止......
    ", Thread.CurrentThread.Name);
                 Interlocked.Decrement(ref poolFlag);  //标记-1
                 try
                 {
                     muxConsole.ReleaseMutex(); //释放阻塞
                 }
                 catch { }
             }
         }
    

      

  • 相关阅读:
    【Lua】LuaForWindows_v5.1.4-46安装失败解决方案
    【C++】指针引发的bug
    【C++】指针引发的bug
    【C++】位操作(3)-获取某位的值
    bzoj1444
    bzoj1758
    bzoj3091
    poj1741 bzoj2152
    bzoj2125 3047
    bzoj3669
  • 原文地址:https://www.cnblogs.com/icejd/p/4354023.html
Copyright © 2020-2023  润新知