AbuMariam
AbuMariam

Reputation: 3678

Creating threads to run algorithm players

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?

Upvotes: 0

Views: 93

Answers (1)

Aify
Aify

Reputation: 3537

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.

Upvotes: 1

Related Questions