using System;
using System.Threading;
class MyThread {
public Thread thrd;
static Semaphore sem = new Semaphore(2, 2);
public MyThread(string name) {
thrd = new Thread(this.run);
thrd.Name = name;
thrd.Start();
}
void run() {
Console.WriteLine(thrd.Name + " is waiting for a permit.");
sem.WaitOne();
Console.WriteLine(thrd.Name + " acquires a permit.");
for(int i=0;i<10;i++) {
Console.WriteLine(thrd.Name + " : " + i);
Thread.Sleep(50);
}
Console.WriteLine(thrd.Name + " releases a permit.");
sem.Release();
}
}
class MainClass {
public static void Main() {
MyThread mt1 = new MyThread("Thread #1");
MyThread mt2 = new MyThread("Thread #2");
MyThread mt3 = new MyThread("Thread #3");
mt1.thrd.Join();
mt2.thrd.Join();
mt3.thrd.Join();
}
}