How to do multiple Thread in a Java Loop

2

Problem description

I'm doing a Pokedex, in which one of its functions is to filter all pokemons of a certain type.

I was able to implement this functionality, but the execution time is not good ... It takes about 25 seconds to go through all the elements, create pokemon objects and add them to a Vector.

I'm trying to solve this problem with the use of Threads. Instead of creating each pokemon sequentially and adding it to the vector, I'm trying to create a loop of repetition that steps into the position of a JSONObject, where the pokemon is located. And after all the threads are completed I will put the resulting 'Pokemon Object' in a Vector ...

My question is:

  • How do I pass this position from JSONObject;
  • How to save Threads results in a Vector, since all use a space in the shared memory;
  • Code I thought

        package model;
    
        import java.io.IOException;
        import java.util.Vector;
    
        import org.json.JSONArray;
        import org.json.JSONException;
        import org.json.JSONObject;
    
        public class Pokemon_Tipo extends RequestClass implements Runnable
        {
            private Vector<Pokemon> SameType_Pokemons = new Vector<Pokemon>();
            private JSONArray root_types;
    
            public Pokemon_Tipo() {}
    
            // Este método é chamado com o tipo de pokemon desejado
            public Vector<Pokemon> Pokemon_type(String tipo)
            {
                try
                {
                    // Nesta url está os link para os pokemons do determinado tipo
                    String data = get("https://pokeapi.co/api/v2/type/"+tipo);
    
                    // Método responsável para retornar um JSONObject com as
                    // informações contidadas na String data
                    JSONObject root = parse(data);
    
                    // Lista de url para todos os pokemons
                    this.root_types = root.getJSONArray("pokemon");
    
                    // loop para entrar em todos url e criar os pokemons
                    for(int i=0; i<root_types.length(); i++)
                    {
                        new Thread(this).start();
                    }
    
                    // Após todas as threads finalizar, retornar esse
                    // vector
                    // Dúvida como esperar todas as threads terminarem?
                    return SameType_Pokemons;
                }
    
                catch (IllegalStateException | IOException | JSONException e)
                {
                    e.printStackTrace();
                }
    
                return null;
            }
    
            //  Thread
            public void run()
            {
                // Pelo a URL uma posição de um JSONArray
                // Dúvida, como passo essa posição i ?
                JSONObject url = root_types.getJSONObject(i)
                        .getJSONObject("pokemon");
    
                // Após a Thread finalizar, salvar o resultado no Vector
                // Dúvida como salvar em um espaço compartilhado?
                SameType_Pokemons.addElement(new Pokemon(url));
            }
    
    
        }
    

    I thought of solving this problem with Threads, if someone has a smarter solution, I'm open to suggestions;)

        
    asked by anonymous 03.11.2018 / 20:11

    0 answers