0

我正在尝试编写一个程序来解决囚犯和开关问题。我创建了一个 SwitchRoom 类..

public class SwitchRoom
{
 private boolean switchA;
 private boolean switchB;

和一个囚犯班

public class Prisoner
{
   public void visitSwitchRoom() {
      // do something with switches

现在我在想我该如何运行它。最好让 Prisoner 类实现 Runnable (将它们的实例变成线程)然后在 Java 程序中生成 23 个线程?

如果这是一个好方法,您能否提供一个代码示例让我开始?

如果这不是正确的方法,你能给我一些关于是什么的指示吗?

4

1 回答 1

1

你的理论方法似乎没问题。

从实现runnable开始,在run()方法中做:

public void run() {
    while (true) {
        if (/*counterperson has 23 counts*/) { break; }
        synchronized (/*your switchroom object here*/) { // this makes it so only one person can flip switches at a time
            // use an if/else to figure out if this person is the "counter" person
            // try to flip a switch/do stuff based on required logic regarding if he is
            // the counter person
        }

        try {
            wait(100); // or however long you want to wait before trying again
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

并制作 23 个这些线程。如果您在每个对象中放置一个布尔值,表示该对象是普通囚犯还是柜台人员,请记住将默认值设置为 false,并将其中一个设置为 true,以便最终退出 while 循环。

于 2015-04-27T20:14:55.020 回答