Return to main() after using start()

Asked

Viewed 421 times

1

After executing the command gerenciador.start(), my program does not return to the function main, and does not print the message is over. It simply executes the command I have spoken. Does anyone know why this happens?

  public class Principal 
{
    private static long startTime = System.currentTimeMillis();

    public static void main(String[] args) 
    {
        Fila sharedLine = new Fila();

        Elevador elev = new Elevador(sharedLine);
        Esquiador gerenciador = new Esquiador(sharedLine);

        gerenciador.start();
        //elev.start();
        System.out.println("acabou");
        long endTime = System.currentTimeMillis();
        System.out.println("It took " + (int)(((endTime - startTime)/1000)/60) + " milliseconds");
    }
}



public class Esquiador extends Thread 
{
     Fila sharedLine;
     static boolean todosEntraram = false;
    //String filaQuePertenco;
    //int idEsquiador;

    public Esquiador(Fila fila) 
    {
        super("Esquiador");
        sharedLine = fila;
        //filaQuePertenco = filaQ;
        //idEsquiador=id;

    }

    public void run()
    {

        for(int i = 0; i < 30; i++)
        {

            try 
             {
                System.out.println("O esquiador está dormindo.");
                Thread.sleep(500);
             } 

            catch (InterruptedException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Esquiadores esquis = new Esquiadores(i);

            //System.out.println("O esquiador "+ esquis.idEsquiador+ " entrou em seu 'run'");
            //while(true)
            //{
                    //política do esquiador para decidir em qual fila ele irá entrar

                    //printando o tamanho de cada fila.
                    System.out.println("O esquiador "+esquis.idEsquiador+" chegou para ingressar numa fila.");
                    System.out.println("Tamanho LS"+sharedLine.elementosLS.size());
                    System.out.println("Tamanho RS"+sharedLine.elementosRS.size());
                    System.out.println("Tamanho LT"+sharedLine.elementosLT.size());
                    System.out.println("Tamanho RT"+sharedLine.elementosRT.size());
                    System.out.println("Esquiador operando ...");


                    if(sharedLine.elementosLS.size()<2*sharedLine.elementosLT.size() && sharedLine.elementosLS.size()<2*sharedLine.elementosRT.size() && sharedLine.elementosLS.size()<sharedLine.elementosRS.size())
                    {
                        //this.filaQuePertenco = "LS";
                        //System.out.println("add ls");
                        sharedLine.adicionaFilaLS(esquis);

                        //printando elementos da fila LS

                    }

                    else if(sharedLine.elementosRS.size()<2*sharedLine.elementosLT.size() && sharedLine.elementosRS.size()<2*sharedLine.elementosRT.size() && sharedLine.elementosRS.size()<=sharedLine.elementosLS.size())
                    {
                        //this.filaQuePertenco = "RS";
                        //System.out.println("add rs");
                        sharedLine.adicionaFilaRS(esquis);

                        //printando elementos da fila RS
                    }

                    else if(sharedLine.elementosLT.size()<=sharedLine.elementosRT.size())
                    {
                        //this.filaQuePertenco = "LT";
                        //System.out.println("add lt");
                        sharedLine.adicionaFilaLT(esquis);

                    }

                    else 
                    {
                        //this.filaQuePertenco = "RT";
                        //System.out.println("add rt");
                        sharedLine.adicionaFilaRT(esquis);
                    }

                    System.out.println("Situação das filas após a operação:");
                    System.out.println("Tamanho LS"+sharedLine.elementosLS.size());
                    System.out.println("Tamanho RS"+sharedLine.elementosRS.size());
                    System.out.println("Tamanho LT"+sharedLine.elementosLT.size());
                    System.out.println("Tamanho RT"+sharedLine.elementosRT.size());
            //}
        }
        Esquiador.todosEntraram = true;
    }
}
  • What is gerenciador.start();???

  • There is a class that I created and put a run() method in it. This.start() manager I called after instantiating an object of the class I spoke, in order to create a thread and run the run method .

  • Put her in the question too! edit

  • All right, man. I’ve completed the main class and added the class I told you about.

1 answer

1


The execution is returning to the method main, but different than you might think. The "finished" line is printed before the first iteration of the thread Esquiador.

I guess you were hoping the method start execute the method run of the thread and only then returned to the main, however, the purpose of a thread is precisely to run in parallel at the same time.

In this case, how do you force a pause right at the beginning of for thread, this makes the method almost invariably main finish before the first sleep.

To wait for a thread to finish, use the method join, thus:

gerenciador.start();
gerenciador.join(); //somente continue depois que a thread finalizar

In addition to this misconception, there are several other problems or at least potential problems:

  1. The time display is dividing the time that is already in milliseconds by 1000 and by 60, so the result will be in hours, not ms.
  2. Your threads seem to be sharing objects and running operations without synchronization and without protection mechanisms against competition issues. In its final implementation, you must ensure that each time you change an object, it occurs in an atomic form.
  3. It’s a little hard to understand the exact intent of the code, but if the original idea was to have 30 skiers, the implementation is completely wrong. You have to create 30 threads and not a thread containing a loop executed 30 times sequentially.
  • That, my intention was to create 30 skiers. In the case , for me to create 30 threads, I would have to instantiate all of them in the main, for example within a loop ?

  • My intention was to create the same 30 threads. In case I would have to instantiate them in main, with a loop of repetition inside which I would give 30 Starts ?

  • @Renandasilvaalves That’s right. Put them in a list, give 30 Tarts and THEN 30 joins to wait for all to finish.

  • My friend, thank you very much ! If it weren’t for that advice of yours, I would take a beautiful 0 tomorrow ! Complicated to deliver a project to the concurrent programming discipline without having thread competition neh kk. Hug !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.