欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#通过Semaphore类控制线程队列的方法

程序员文章站 2023-11-25 16:17:34
本文实例讲述了c#通过semaphore类控制线程队列的方法。分享给大家供大家参考。具体实现方法如下: using system; using system.c...

本文实例讲述了c#通过semaphore类控制线程队列的方法。分享给大家供大家参考。具体实现方法如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.io;
using system.diagnostics;
using system.threading;
using system.componentmodel;
using system.collections;
using system.net;
using system.runtime.serialization;
using system.xml;
using system.globalization;
using system.text.regularexpressions;
using system.data;
using system.data.sqlclient;
namespace consoleapp
{
 /// <summary>
 /// 线程控制队列
 /// semaphore类
 /// </summary>
 class program
 {
  static semaphore semaphore;
  static void main(string[] args)
  {
   semaphore = new semaphore(0, 2);
   thread thread;
   for (int i = 0; i <= 5; i++)
   {
    thread = new thread(new parameterizedthreadstart(run));
    thread.start("thread_"+i.tostring());
   }
   semaphore.release(2);
   console.readline();
  }
  static void run(object obj)
  {
   semaphore.waitone();
   console.writeline("thread " + obj.tostring() + " into the method");
   system.threading.thread.sleep(5000);   
   console.writeline("_thread " + obj.tostring() + " leave the method");
   semaphore.release();
  }
 }
}

希望本文所述对大家的c#程序设计有所帮助。