package servlet.test;
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Semaphore semaphore = new Semaphore(2);
CustomThread ct1 = new CustomThreadSemaphore(semaphore, "A Thread");
ct1.start();
CustomThread ct2 = new CustomThreadSemaphore(semaphore, "B Thread");
ct2.start();
CustomThread ct3 = new CustomThreadSemaphore(semaphore, "C Thread");
ct3.start();
}
}
class CustomThreadSemaphore extends Thread {
private Semaphore semaphore;
public CustomThreadSemaphore(Semaphore semaphore, String name) {
setName(name);
this.semaphore = semaphore;
}
@Override
public void run() {
System.out.println(getName() + " is waiting.");
try {
semaphore.acquire();
System.out.println(getName() + " is service.");
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println(getName() + " is done.");
semaphore.release();
}
}
}