How to Make Multiple Threads in a Java Loop

Asked

Viewed 321 times

2

Description of the Problem

I’m making a Pokedex, in which one of its features is to filter all the Pokemons of a certain type.

I managed to implement this functionality, but the execution time is not good... It takes about 25 seconds to go through all the elements, create Pokemons 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 to the vector, I am trying to create a loop that passes the position of a Jsonobject, where the Pokemon is. And after all Threads are completed I will place the resulting 'Pokemon Object' in a Vector...

My question is:

  1. How do I pass this Jsonobject position;
  2. How to save Threads results to a Vector, since everyone uses a space in 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 about solving this problem with Threads, in case someone has a smarter solution, I’m open to suggestions ;)

  • 3

    Paralysis alone may not be the best solution to your problem. Processing the URLS in parallel will help with the load speed, but at some point you will saturate the connection limit and your application will basically have multiple threads blocked in IO. Some ideas: 1. Download the data and record locally; 2. If the idea is to have Pokédex automatically updated with new Pokémon you can do this update process on background; 3. Do not load all Pokémon at once. Open on demand or implement a pagination logic

No answers

Browser other questions tagged

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