您能否解释一下为什么在下面的程序中以这种方式实现Runnable接口是一个错误的设计决定?凭直觉,如果我必须自己编写此代码,则可以将Hotel成为自己的类,并在实现Runnable的新类中编写run()的规范。但是,我无法真正解释下面的代码为什么是一个错误的设计决策。
该班级将模拟一个酒店,其中要排队等候人员并列出房间。有几个在不同线程上运行的“办公桌”,每个办公桌负责将人员从队列中移出并检入可用的房间。为简单起见,不包括退房。方法的实现无关紧要(请相信它是线程安全的),这个问题是关于将run()放入Hotel类的设计决策的。
public class Hotel implements Runnable {
private final static int NR_ROOMS = 10;
private final Person [] rooms = new Person [ NR_ROOMS ];
private final List < Person > queue = new ArrayList < >();
private final Lock queueLock = new ReentrantLock ();
private boolean occupied (int i) {
return ( rooms [i] != null);
}
private int checkIn ( Person p) {
// add Person to a free room
}
private void enter ( Person p) {
// add a person to the waiting queue
}
// every desk employee should run as a separate thread
@Override
public void run () {
// remove guests from the queue and check them in
}
}