看一下1Z0-804考试的一些文献,我找到了这个例子的问题:
Consider the following program:
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);
}
}
}
Which one of the options is true if you replace the statement #1 with the following statement? Semaphore machines = new Semaphore(2, true);
Omitting the answers
关于正确答案的解释引起了我的注意:
The second parameter states the fairness policy of the semaphore object. However, there
are two permits for the semaphore object; so you cannot predict the order in which waiting
people will get the permission to access the ATM.
我会说,由于线程的非确定性,不能预测顺序,不是因为信号量中的许可数量,而且公平参数保证等待线程以它们获取的相同顺序被唤醒信号量,但仍然无法确定收单.我的解释是否正确?
解决方法:
据我所知,是的,你的想法是正确的,因为公平的信号量使用FairSync,并且它’获取机制不会在可用许可数量上转发,而只在线程队列中的第一个线程上转发:
protected int tryAcquireShared(int acquires) {
for (;;) {
if (getFirstQueuedThread() != Thread.currentThread() &&
hasQueuedThreads())
return -1;
....
标签:java,concurrency,semaphore
来源: https://codeday.me/bug/20190709/1409636.html