packageconcurrent.semaphore;importjava.util.concurrent.Semaphore;importjava.util.concurrent.TimeUnit;/*** 排队取票的人*/
public class Man implementsRunnable {/*** 取票的人的姓名*/
privateString name;/*** 必须要的取票证明*/
privateSemaphore semaphore;/*** 最后的行为
* 0 : 取到票为止
* 1 : 排队的时候不耐烦, 走了, 买飞机票去了
* 2 : 排队的时候突然有事, 回家去了*/
private intbehav;public Man(String name, Semaphore semaphore, intbehav) {this.name =name;this.semaphore =semaphore;this.behav =behav;
}
@Overridepublic voidrun() {switch(behav) {/*** 坚持到底*/
case 0:/*** 排队, 坚持不懈 , 就是要拿到许可证*/semaphore.acquireUninterruptibly();try{
Thread.sleep(1000);
System.out.println("我正在取票啦!! " +name);
}catch(InterruptedException e) {
e.printStackTrace();
}
semaphore.release();
System.out.println("哇, 我终于取到票啦!! " +name);break;/*** 买不到我就坐飞机*/
case 1:try{if (semaphore.tryAcquire(1, TimeUnit.SECONDS)) {
System.out.println("我正在取票啦!! " +name);
Thread.sleep(2000);
semaphore.release();
System.out.println("哇, 我终于取到票啦!! " +name);
}else{
System.out.println("我不取了, 坐飞机去啦!! " +name);
}break;
}catch(InterruptedException e) {
e.printStackTrace();
}/*** 买不到我就回家*/
case 2:try{
semaphore.acquire();try{
Thread.sleep(1000);
System.out.println("我正在取票啦!! " +name);
}catch(InterruptedException e) {
e.printStackTrace();
}
semaphore.release();
System.out.println("哇, 我终于取到票啦!! " +name);
}catch(InterruptedException e) {//e.printStackTrace();
System.out.println("算了, 回家吃饭去了 " +name);
}break;/*** 不知道这个人是干嘛的, 黄牛吧*/
default:break;
}
}
}