How to run multiple FORs at once

0

In the code below I have 4 for and they run in sequence, but I need them to run all at the same time.

public class main 
{
public static void main(String[] args)
{
    long init  = System.currentTimeMillis(); 
    ataque(999999, 999999);
    long end  = System.currentTimeMillis(); 
    long diff = end - init;
    System.out.print("Demorou " + (diff / 1000) + " segundos");
}
public static void ataque(int limite, int busca)
{
    int for1 = 0;
    int for2 = limite / 4;
    int for3 = for2 + for2;
    int for4 = for2 = for3;

    for(int i = for1; i < for2; i++)
    {
        /*if(i == busca)
        {
            break;
        }*/

        System.out.println(i + " de " + busca + "\r"); 
    }
    for(int i = for2; i < for3; i++)
    {
        /*if(i == busca)
        {
            break;
        }*/

        System.out.println(i + " de " + busca + "\r"); 
    }
    for(int i = for3; i < for4; i++)
    {
        /*if(i == busca)
        {
            break;
        }*/

        System.out.println(i + " de " + busca + "\r"); 
    }
    for(int i = for4; i < limite; i++)
    {
        /*if(i == busca)
        {
            break;
        }*/

        System.out.println(i + " de " + busca + "\r"); 
    }
}
}
    
asked by anonymous 06.07.2015 / 22:38

1 answer

2

You can create 4 Threads with Runnable . Note not will be exactly the same time, but one will not have to wait for another, eg:

new Thread(new Runnable(){
    @Override
    public void run() {
        for(int i = for1; i < for2; i++)
        {
            System.out.println(i + " de " + busca + "\r"); 
        }
    }
}).start();

new Thread(new Runnable(){
    @Override
    public void run() {
        for(int i = for2; i < for3; i++)
        {
            System.out.println(i + " de " + busca + "\r"); 
        }
    }
}).start();

However if you really need them to be at the same time, you will have to create all events within a single loop and use a boolean variable to check if at least one of the conditions has entered a IF :

bool testIfs = false;
int increment1 = 0;
int increment2 = 0;

while (true) {
    if (increment1 < for2) {
        //Se entrar na condição então não irá lançar o break
        testIfs = true;

        System.out.println(increment1 + " de " + busca + "\r"); 

        increment1++;
    }

    if (increment2 < for3) {
        //Se entrar na condição então não irá lançar o break
        testIfs = true;

        System.out.println(increment2 + " de " + busca + "\r"); 

        increment2++;
    }

    if (testIfs == false) {
       //Se o loop não entrou em nenhuma das if então é executado o break pra poder parar o loop
       break;
    }

    //Se não houve break então testIfs volta a ser false pra testar novamente o loop
    testIfs = false;
}

In this example, I've just added two conditions to understand, but you can add multiple "ifs".

    
06.07.2015 / 22:44