您的位置:首页 > 编程语言 > C#

一个多线程的小例子---C#高级编程学习

2011-12-29 17:46 253 查看
C#高级编程学习时的小例子:

public  void main()
{
int threadCount = 6;
int semaphoreCount = 3;
var semaphore = new SemaphoreSlim(semaphoreCount,
semaphoreCount);
var threads = new Thread[threadCount];

for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(threadMain);
threads[i].Start(semaphore);
}

for (int i = 0; i < threadCount; i++)
{
threads[i].Join();
}
Console.WriteLine("All threads Finished");
}

public void threadMain(object o)
{
SemaphoreSlim semaphore = o as SemaphoreSlim;
Trace.Assert(semaphore != null, "o must be a Semaphore type");
bool isCompleted = false;

while(!isCompleted)
{
if (semaphore.Wait(600))
{
try
{
Console.WriteLine("Thread {0} locks the semaphore",
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(2000);
}
finally
{
semaphore.Release();
Console.WriteLine("Thread {0} releases the semaphore",
Thread.CurrentThread.ManagedThreadId);
isCompleted = true;
}
}
else
{
Console.WriteLine("TimeOut for Thread {0};Wait again",
Thread.CurrentThread.ManagedThreadId);
}

}

}

结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: