一个多线程的小例子---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); } } }
结果:
相关文章推荐
- 学习VC多线程时随手写的一个小例子
- C# 一个简单的多线程例子
- 关于多线程程序中使用volatile关键字的一个小例子
- 一个java多线程的例子
- 一个例子展开,介绍Linux下面线程的操作、多线程的同步和互斥。
- 一个winform中多线程的例子
- 一个生产者与消费者模型的多线程例子程序
- C# 一个简单的多线程例子
- 一个例子玩转linux多线程问题(创建 执行 条件变量 ......)
- 关于在多线程情况下同步爬虫爬取结果的一个例子
- 多线程采用不同的方法操作一个资源的例子
- C- 一个多线程的例子
- java 多线程——一个定时调度的例子
- 一个简单的多线程例子-互斥量
- 标准C / C + +运行期库原先并不是设计用于多线程应用程序的唯一一个例子
- 多线程死锁的一个简单例子
- 一个验证HashMap在多线程环境下线程不安全的例子及dump分析
- 一个实现多线程的例子
- 【python学习】多线程 与 面向对象 结合的一个经典例子
- 一个多线程的经典例子