【发布时间】:2013-05-30 13:09:54
【问题描述】:
查看 1Z0-804 考试的一些文献,我找到了这个示例问题:
考虑以下程序:
class ATMRoom {
public static void main(String []args) {
Semaphore machines = new Semaphore(2); //#1
new Person(machines, "Mickey");
new Person(machines, "Donald");
new Person(machines, "Tom");
new Person(machines, "Jerry");
new Person(machines, "Casper");
}
}
class Person extends Thread {
private Semaphore machines;
public Person(Semaphore machines, String name) {
this.machines = machines;
this.setName(name);
this.start();
}
public void run() {
try {
System.out.println(getName()
+ " waiting to access an ATM machine");
machines.acquire();
System.out.println(getName()
+ " is accessing an ATM machine");
Thread.sleep(1000);
System.out.println(getName()
+ " is done using the ATM machine");
machines.release();
} catch(InterruptedException ie) {
System.err.println(ie);
}
}
}
如果将第 1 条语句替换为以下语句,哪一个选项是正确的?
Semaphore machines = new Semaphore(2, true);省略答案
正确答案的解释引起了我的注意:
第二个参数说明信号量对象的公平策略。但是,那里 是信号量对象的两个许可;所以你无法预测等待的顺序 人们将获得访问 ATM 的权限。
我会说不能仅仅因为线程的不确定性而预测顺序,而不是因为信号量中的许可数量,并且公平参数保证等待线程以相同的顺序被唤醒他们获取了信号量,但仍然无法确定获取顺序。我的解释正确吗?
【问题讨论】:
标签: java concurrency semaphore