JAVA练习 :公交车,司机和售票员信号量问题
import java.util.concurrent.Semaphore;
public class BusTest {
public static void main(String[] args)throws Exception{
Semaphore doorClosed = new Semaphore(1);
Semaphore carStoped = new Semaphore(1);
new Thread(){
public void run(){
try {
//初始车是停的
carStoped.acquire();
while(true){
doorClosed.acquire();
System.out.println("司机:乘客上完了,开车。");
Thread.sleep(1000);
System.out.println("司机:到站了,停车。");
Thread.sleep(1000);
carStoped.release();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
new Thread(){
public void run(){
while(true){
try {
carStoped.acquire();
System.out.println("售票员:开门了。");
Thread.sleep(1000);
System.out.println("售票员:买票了。");
Thread.sleep(1000);
System.out.println("售票员:关门了。");
Thread.sleep(1000);
doorClosed.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/34346.html