【发布时间】:2021-01-24 06:34:03
【问题描述】:
我有一个用例,我正在为用户实现对 ATM 机的访问,使用 java.util.concurrent 包中的 Semaphore 类作为锁,即锁定对资源的访问。
任何想要访问锁定的资源的线程在访问资源之前调用acquire()方法,获取锁并通过调用release()方法释放锁,完成后任务。
实施代码:
import java.util.concurrent.Semaphore;
class ATMMachine {
public static void main(String []args) {
Semaphore machines = new Semaphore(1,true);
new Person(machines, "A");
new Person(machines, "B");
new Person(machines, "C");
}
}
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()+ " is waiting to access the ATM machine");
machines.acquire();
System.out.println(getName()+ " is accessing the ATM machine");
Thread.sleep(1000);
System.out.println(getName()+ " is done using the ATM machine");
machines.release();
} catch(InterruptedException ie) {
System.err.println(ie);
}
}
}
输出:
A is waiting to access the ATM machine
C is waiting to access the ATM machine
B is waiting to access the ATM machine
A is accessing the ATM machine
A is done using the ATM machine
C is accessing the ATM machine
C is done using the ATM machine
B is accessing the ATM machine
B is done using the ATM machine
问题:每次我运行程序时,输出都会发生变化。但是,我想确保按顺序向用户授予对机器的访问权限:A → 然后 B → 最后是 C
注意:我在构造函数中设置了fair参数为true,这应该保证FIFO按照线程被请求的顺序。但这似乎不起作用。
请求您帮助我解决问题的任何建议/参考。谢谢!
【问题讨论】:
标签: java multithreading java-8 concurrency semaphore