1.
public class Semaphore implements java.io.Serializable{
public Semaphore(int permits){};
public void acquire() throws InterruptedException{};
public int availablePermits(){
return 0;
};
public void release(){};
}
2.
public class SemaphoreTest1 {
Semaphore semaphore = new Semaphore(2);
public static void main(String[] args) {
SemaphoreTest1 t = new SemaphoreTest1();
new Thread(t::stop,"预A-SY281").start();
new Thread(t::stop,"预B-SY666").start();
new Thread(t::stop,"预C-SY777").start();
new Thread(t::stop,"预D-SY888").start();
new Thread(t::stop,"预E-SY999").start();
new Thread(t::stop,"预F-SY595").start();
new Thread(t::stop,"预G-SY317").start();
}
void stop(){
String t = Thread.currentThread().getName();
try {
System.out.println(t + ":尝试进入停车场...");
semaphore.acquire();
long time = (long) (Math.random() * 50 + 10);
System.out.println(t + ":进入了停车场,停车" + time + "秒...");
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e){
e.printStackTrace();
} finally {
System.out.println(t + ":开始驶离停车场...");
semaphore.release();
System.out.println(t + ":离开了停车场!");
}
}
}
3.
public class SemaphoreTest2 {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <= 10; i++) {
new Thread(new MyRunnable(semaphore),"第" + i + "个人").start();
}
}
static class MyRunnable implements Runnable{
private Semaphore semaphore;
public MyRunnable(Semaphore semaphore){
this.semaphore = semaphore;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
int availablePermits = semaphore.availablePermits();
if (availablePermits > 0){
System.out.println(name + "无人,可用");
} else {
System.out.println(name + "有人,请排队。。。\t");
}
try {
semaphore.acquire();
System.out.println(name + "轮到我了");
Thread.sleep(1000);
System.out.println(name + "使用完毕\t");
} catch (InterruptedException e){
} finally {
semaphore.release();
}
}
}
}