Sort the output order of an array

-1

Hi, I'm stuck in some parts of my program and now I have the next part of my program:

public class Relleus {

public static void main(String[] args) throws InterruptedException {
    Testimoni c = new Testimoni();
    int numMembres = 5; //la familia pot ser més gran o més petita

    //Es creen el membres de la família, se'ls dona un nom i es posen a mirar la tele
    Corredor[] membre = new Corredor[numMembres];
        for(int i=1; i<numMembres; i++) {
        membre[i] = new Corredor(c);
        membre[i].setName("CORREDOR : "+i);
        membre[i].start();


    }
    //Esperem que tots acabin de mirar la tele
    for(int i=1; i<numMembres; i++) {
        membre[i].join();
    }

    System.out.println("Carrera acabada!!");

  }
}




public class Corredor extends Thread {

    Testimoni comandament;
    static int canal;

    public Corredor(Testimoni c) {
        comandament = c;
        canal = 0;
    }

    @Override
    public void run() {
     // 3, 2, 1, go, go, go

       System.out.println("Escriu go a la pantalla..");



        int veces = comandament.agafa();
        System.out.println(getName() + " esta corren");

        //Mira la tele
        try {
            Thread.sleep((long) (Math.random() * 350) + 300);  //utilitzem el mètode sleep per suspendre l'execució del Thread un temps aleatori de ms
        } catch (InterruptedException e) {
            System.out.println("Error!!!");

        }
        if (veces == 0 || veces == 1 || veces == 2) {
            System.out.println("Pasa el testimoni al seguent corredor:");
            //Deixa el comandament
            comandament.deixa();

        } else {
            comandament.deixa();
        }
        {

        }
    }
}


public class Testimoni  {
   /*
    * Modifiqueu i afegiu el codi necessari per implementar la classe 
    * Comandament.
    */
    boolean avalible = true;
    int PasarTest = 0;

    synchronized int agafa() {

    while (avalible == false) {
        try {
            wait();
        } catch (InterruptedException e) {
        }
    }

    avalible = false;
    notify();
    return PasarTest;

}

        synchronized void deixa() {
    avalible = true;
    ++ PasarTest;
    notify();
}
    }

I have an array that shows 4 runners.

runner 1 runner 2 runner 3 Runner 4

But when I show them on the screen, I mix them.

How can I avoid it?

Can you give me an idea?

They are threads and I'm a bit lost. Surely it is silly but I do not know how to put the truth ..

thanks!

    
asked by Montse Mkd 13.03.2018 в 17:55
source

1 answer

0

Greetings Montse Mkd.

When starting all Thread it is not possible to know exactly when this thread will be executed, the only thing we know is that the Thread will be executed as soon as we call the start method, basically it is normal to run in disorder (for reasons of concurrence).

Going back to your case and as I understand it, you need to execute all the threads at the same time, but these must run in order, that is, wait for Runner 1 to finish running so that the next runner (with top number of + 1, that is, Runner 2), start running and so on until the end.

Looking at your code, I realized that you never do the corridor check (although it does exist, but you did not take it into account) right here:

int veces = comandament.agafa();

That method returns an integer (and in my opinion is the runner number that should run according to the order), however, what would happen if Runner 3 is ready to run but it is not his turn? Exactly that's what you're not checking, you're letting it run!

After doing several tests, I think you should take into account adding an ID (of the whole type) to each runner, which will be his "number" and thus know who is who. Based on your code, I got the following result:

As you can see, the competition is still there, since the 4 runners ( Thread ) were run in disorder, however, at the time of running, they did so in order according to their race number ( ID ).

Basically, only one variable of integer type was added to the class Corredor and then a while was used to check if the integer matched its number, and if so, then it's your turn and you should run.

public class Corredor extends Thread {

    Testimoni comandament;
    static int canal; // esta variable no sé para qué la utilizarás
    int id;

    public Corredor(Testimoni c) {
        comandament = c;
        canal = 0;
    }

    @Override
    public void run() {
        System.out.println(getName() + " está listo para correr");

        while (comandament.agafa() != id) {
            comandament.PasarTest--;
            comandament.deixa();
        }

        System.out.println("¡" + getName() + " está corriendo!");

        try {
            Thread.sleep((long) (Math.random() * 350) + 300);
        } catch (InterruptedException e) {
            System.out.println("¡Error!");

        }

        comandament.deixa();
    }
}

And the class Relleus :

public class Relleus {

    public static void main(String[] args) throws InterruptedException {
        Testimoni c = new Testimoni();
        int numMembres = 4;

        Corredor[] membre = new Corredor[numMembres];
        for (int i = 0; i < numMembres; i++) {
            membre[i] = new Corredor(c);
            membre[i].id = i; // se agrega el ID según el orden
            membre[i].setName("CORREDOR " + (i + 1));
            membre[i].start();
        }

        for (int i = 0; i < numMembres; i++) {
            membre[i].join();
        }

        System.out.println("¡Carrera acabada!");
    }
}

The code that I attached is only an example method, since there are no drastic changes in the structure, simply existing methods were recycled to achieve the objective of explaining why your problem happens, it is at your disposal to use it as you wish, however, I recommend you to investigate on your own a better way to accommodate the structure of your program.

Evidence:

    
answered by 14.03.2018 в 08:54