0

I am trying to write a program which implements a solution for the Prisoners and switches problem. I created a SwitchRoom class..

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

and a prisoner class

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

Now I am thinking how exactly I can run this. Would it be best to have Prisoner class implement Runnable (make instances of them into threads) and then spawn 23 threads in a java program?

If this is a good approach could you please provide a code sample to get me started?

If it is not the right way could you give me some pointers on what is?

AbuMariam
  • 3,282
  • 13
  • 49
  • 82
  • honestly i think this question is too broad and should be closed. – OPK Apr 27 '15 at 18:47
  • Do players (`Prisoner`) play at the same time? Or one plays and the others are blocked? – MCHAppy Apr 27 '15 at 18:49
  • @Chaker, I believe one plays while others are blocked – AbuMariam Apr 27 '15 at 19:30
  • @Hashap, please let me know how I can make it more general. What I am looking for is really the code on how to create threads for the prisoners or someone to tell me the whole concept is way off. – AbuMariam Apr 27 '15 at 19:31
  • Did you want to make it "realistic" and have each player go in at random times? Because if you just want to show that it can be solved, a for/while loop will work... – Aify Apr 27 '15 at 19:34
  • @Aify, yes I prefer to have it realistic and have players going in at random time. – AbuMariam Apr 27 '15 at 20:01

1 Answers1

1

Your theorized approach seems to be alright.

Start with implementing runnable, and in the run() method do:

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();
        }
    }
}

and make 23 of these threads. If you put a boolean in each object that represents if the object is a normal prisoner or the counter person, remember to set the default to false, and set one of them to true so that eventually you break out of the while loop.

Aify
  • 3,543
  • 3
  • 24
  • 43