java semaphore 等待_Java线程--Semaphore使用

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;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值