java信号量顺序_java – 信号量的大小可以与线程的执行顺序相关吗?

看一下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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值