How to do a while without locking the application in Java

Asked

Viewed 183 times

-1

I’m building an application in college that I need to run a code for 2 minutes and minute to minute to do an evaluation of the system and the variables that are in it. I’ve looked on the Internet, some say to use new Thread() others to use new Runnable(), others to use the 2 forms and yet I arrive at a solution.

I made an example with the minimum that I need for my application to work, I just need to instantiate this class 2 times and that the 2 can print any content on the console at the same time.

package teste;

public class Log {

    public boolean parar;

    public Log(String n) {

        SimpleDateFormat f = new SimpleDateFormat("ss");
        parar = false;

        int dTest, dNow = Integer.parseInt(f.format(Calendar.getInstance().getTime()));

        while (!parar) {

            dTest = Integer.parseInt(f.format(Calendar.getInstance().getTime()));

            if (dNow != dTest) {
                dNow = dTest;
                System.out.println(dNow + " | " + n);
            }

        }

    }

}

public class Teste {

    public static void main(String[] args) {

        System.out.println("teste de classe (1 para o sistema)");

        Log foo = new Log("foo"), bar = new Log("bar");

        Scanner scan = new Scanner(System.in);

        while (scan.nextInt() != 1) {
            System.out.println("------");
        }

        Runtime.getRuntime().exit(0);

    }

}

What is the best way to do this (or at least one that runs the 2 instances and my system is open and can read it, like a real-time reading)?

  • You can’t use a while as a real-time function, it will make you lock without a shadow of a doubt

  • You can put a function that runs every so many times to do what you want, with a time of 10, 20 or 30 seconds, a while will do the process over a thousand times every second, this is unnecessary and no machine can handle

  • I don’t understand what you’re trying to do. This code only has one thread, so I don’t understand what you’re trying to parallelize. Besides, I don’t understand what your class is Log is waiting and why.

  • Besides, there’s nowhere you can go parar = true; or even try to do it. That way, the function Log will always be an infinite bond.

  • 1

    I see here a XY problem: "I’m building an application in college that I need to run a code for 2 minutes and minute to minute to do an evaluation of the system and the variables that are in it." - That’s the problem X, is what you need to solve. "I made an example with the minimum that I need for my application to work, I just need to instantiate this class 2 times and that the 2 can print any content on the console at the same time." - This is the Y, something you think can solve the problem, but you don’t know how or why.

1 answer

2


First, I see here a XY problem:

I’m building an application in college that I need to run a code for 2 minutes and minute to minute to do an evaluation of the system and the variables that are in it.

That’s the problem X, is what you need to solve.

I made an example with the minimum that I need for my application to work, I just need to instantiate this class 2 times and that the 2 can print any content on the console at the same time.

That’s the Y problem, something you think can solve the problem, but you don’t know exactly how or why.

I’ll come up with a solution to your problem X:

public class Avaliador {

    private Avaliador() {
        throw new UnsupportedOperationException();
    }

    public static void avaliar(
            Trabalho trabalho,
            int intervalo)
    {
        Runnable r = () -> {
            while (!trabalho.terminou()) {
                System.out.println(trabalho.getStatus());
                try {
                    Thread.sleep(intervalo * 1000);
                } catch (InterruptedException e) {
                    break;
                }
            }
            System.out.println(trabalho.getStatus());
        };
        Thread t = new Thread(r);
        t.start();
    }
}
public interface Trabalho {
    public boolean terminou();
    public String getStatus();
}
public class TrabalhoPesado implements Trabalho {

    private final String nome;
    private final int tamanho;
    private final Thread trabalhador;
    private volatile int tempoQuePassou;

    private TrabalhoPesado(String nome, int tamanho) {
        this.nome = nome;
        this.tamanho = tamanho;
        this.trabalhador = new Thread(this::trabalhar);
    }

    private void trabalhar() {
        while (tempoQuePassou < tamanho) {
            try {
                tempoQuePassou++;
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                break;
            }
        }
    }

    public static TrabalhoPesado novoTrabalho(String nome, int tamanho) {
        TrabalhoPesado tp = new TrabalhoPesado(nome, tamanho);
        tp.trabalhador.start();
        return tp;
    }

    @Override
    public boolean terminou() {
        return !trabalhador.isAlive();
    }

    @Override
    public String getStatus() {
        return "Trabalho: " + nome + ". Tempo que passou: " + tempoQuePassou + ". Terminou: " + terminou();
    }
}
public class Teste {
    public static void main(String[] args) {
        Trabalho t1 = TrabalhoPesado.novoTrabalho("Azul", 120);
        Avaliador.avaliar(t1, 10);
        Trabalho t2 = TrabalhoPesado.novoTrabalho("Verde", 60);
        Avaliador.avaliar(t2, 1);
    }
}

Let this program run for two minutes and it will produce that output (or something like that, output lines of different jobs done at the same time may appear in separate orders):

Trabalho: Azul. Tempo que passou: 1. Terminou: false
Trabalho: Verde. Tempo que passou: 1. Terminou: false
Trabalho: Verde. Tempo que passou: 2. Terminou: false
Trabalho: Verde. Tempo que passou: 3. Terminou: false
Trabalho: Verde. Tempo que passou: 4. Terminou: false
Trabalho: Verde. Tempo que passou: 5. Terminou: false
Trabalho: Verde. Tempo que passou: 6. Terminou: false
Trabalho: Verde. Tempo que passou: 7. Terminou: false
Trabalho: Verde. Tempo que passou: 8. Terminou: false
Trabalho: Verde. Tempo que passou: 9. Terminou: false
Trabalho: Verde. Tempo que passou: 10. Terminou: false
Trabalho: Azul. Tempo que passou: 10. Terminou: false
Trabalho: Verde. Tempo que passou: 11. Terminou: false
Trabalho: Verde. Tempo que passou: 12. Terminou: false
Trabalho: Verde. Tempo que passou: 13. Terminou: false
Trabalho: Verde. Tempo que passou: 14. Terminou: false
Trabalho: Verde. Tempo que passou: 15. Terminou: false
Trabalho: Verde. Tempo que passou: 16. Terminou: false
Trabalho: Verde. Tempo que passou: 17. Terminou: false
Trabalho: Verde. Tempo que passou: 18. Terminou: false
Trabalho: Verde. Tempo que passou: 19. Terminou: false
Trabalho: Verde. Tempo que passou: 20. Terminou: false
Trabalho: Azul. Tempo que passou: 20. Terminou: false
Trabalho: Verde. Tempo que passou: 21. Terminou: false
Trabalho: Verde. Tempo que passou: 22. Terminou: false
Trabalho: Verde. Tempo que passou: 23. Terminou: false
Trabalho: Verde. Tempo que passou: 24. Terminou: false
Trabalho: Verde. Tempo que passou: 25. Terminou: false
Trabalho: Verde. Tempo que passou: 26. Terminou: false
Trabalho: Verde. Tempo que passou: 27. Terminou: false
Trabalho: Verde. Tempo que passou: 28. Terminou: false
Trabalho: Verde. Tempo que passou: 29. Terminou: false
Trabalho: Verde. Tempo que passou: 30. Terminou: false
Trabalho: Azul. Tempo que passou: 30. Terminou: false
Trabalho: Verde. Tempo que passou: 31. Terminou: false
Trabalho: Verde. Tempo que passou: 32. Terminou: false
Trabalho: Verde. Tempo que passou: 33. Terminou: false
Trabalho: Verde. Tempo que passou: 34. Terminou: false
Trabalho: Verde. Tempo que passou: 35. Terminou: false
Trabalho: Verde. Tempo que passou: 36. Terminou: false
Trabalho: Verde. Tempo que passou: 37. Terminou: false
Trabalho: Verde. Tempo que passou: 38. Terminou: false
Trabalho: Verde. Tempo que passou: 39. Terminou: false
Trabalho: Verde. Tempo que passou: 40. Terminou: false
Trabalho: Azul. Tempo que passou: 40. Terminou: false
Trabalho: Verde. Tempo que passou: 41. Terminou: false
Trabalho: Verde. Tempo que passou: 42. Terminou: false
Trabalho: Verde. Tempo que passou: 43. Terminou: false
Trabalho: Verde. Tempo que passou: 44. Terminou: false
Trabalho: Verde. Tempo que passou: 45. Terminou: false
Trabalho: Verde. Tempo que passou: 46. Terminou: false
Trabalho: Verde. Tempo que passou: 47. Terminou: false
Trabalho: Verde. Tempo que passou: 48. Terminou: false
Trabalho: Verde. Tempo que passou: 49. Terminou: false
Trabalho: Verde. Tempo que passou: 50. Terminou: false
Trabalho: Azul. Tempo que passou: 50. Terminou: false
Trabalho: Verde. Tempo que passou: 51. Terminou: false
Trabalho: Verde. Tempo que passou: 52. Terminou: false
Trabalho: Verde. Tempo que passou: 53. Terminou: false
Trabalho: Verde. Tempo que passou: 54. Terminou: false
Trabalho: Verde. Tempo que passou: 55. Terminou: false
Trabalho: Verde. Tempo que passou: 56. Terminou: false
Trabalho: Verde. Tempo que passou: 57. Terminou: false
Trabalho: Verde. Tempo que passou: 58. Terminou: false
Trabalho: Verde. Tempo que passou: 59. Terminou: false
Trabalho: Verde. Tempo que passou: 60. Terminou: false
Trabalho: Azul. Tempo que passou: 60. Terminou: false
Trabalho: Verde. Tempo que passou: 60. Terminou: true
Trabalho: Azul. Tempo que passou: 70. Terminou: false
Trabalho: Azul. Tempo que passou: 80. Terminou: false
Trabalho: Azul. Tempo que passou: 90. Terminou: false
Trabalho: Azul. Tempo que passou: 100. Terminou: false
Trabalho: Azul. Tempo que passou: 110. Terminou: false
Trabalho: Azul. Tempo que passou: 120. Terminou: false
Trabalho: Azul. Tempo que passou: 120. Terminou: true

Note that you can adjust the numbers of Avaliador to define the frequency at which he checks the progress of the work. When he realizes that the work is finished, he stops. You can perform several works in parallel, each with its own independent evaluator from the others.

The interface Trabalho specifies that a job must have a method to determine whether it has already finished and one to give the status to be viewed by Avaliador. The implementation TrabalhoPesado here does nothing very important, but you will probably use a different implementation of this interface.

  • That moment you know what you need but can not explain... Thank you very much partner!

Browser other questions tagged

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