Start a thread again

Asked

Viewed 195 times

2

I have an event on the start button, every time I press 3 threads are generated that start the count from 30 to 0, to which reach 1º to 0 wins. But however I press the start button a few times and the count starts at 30 and does everything the same, if I keep pressing the start button one or two more times it will errors and stops running the thread. My question is: I start three threads when I press the start button but to do it again in the same frame you have to kill the threads or interrupt them?

C1,C2,C3 are Horse objects.

  • Corridacavalos class

    iniciar.addActionListener(new ActionListener(){
    
        @Override
        public void actionPerformed(ActionEvent e) {
            c1.setMovimentos(30);
            c2.setMovimentos(30);
            c3.setMovimentos(30);
    
            c1.start();         //start iniciar o run da thread cavalo c1 - classe cavalo
            c2.start();
            c3.start();
        }
    
    
    });
    
  • Horse class extends thread - where I define instructions for it

    @Override
    public void run(){
    try {
        while(movimentos > 0){
            sleep((long) (500*Math.random()));
            movimentos--;
            textField.setText(Integer.toString(movimentos));        //Converter Inteiro para String
        }
    } catch (InterruptedException e) {
        interrupt();
    }
    } 
    

1 answer

2


Yes, you need to finish the threads. More than that, you should declare your Horse instances within actionPerformed(), so that each click creates and runs new threads:

iniciar.addActionListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent e) {
        if (c1 != null) {
            c1.setMovimentos(0);
            c1.interrupt();
            c2.setMovimentos(0);
            c2.interrupt();
            c3.setMovimentos(0);
            c3.interrupt();
        }
        c1 = new Cavalo();
        c2 = new Cavalo();
        c3 = new Cavalo();

        c1.setMovimentos(30);
        c2.setMovimentos(30);
        c3.setMovimentos(30);

        c1.start();         //start iniciar o run da thread cavalo c1 - classe cavalo
        c2.start();
        c3.start();
    }


});

Note: the command interrupt() below the catch is unnecessary.

  • why is the Internet() unnecessary?

  • 1

    Because when the InterruptedException thread is already stopped. There is no need to stop it again. Simply interrupt() calls within actionPerformed(), which are the ones that cause the launch of InterruptedException.

  • 1

    In fact also these interrupted() may not be enough. I added the behavior of zeroing the movements, which makes the threads go out of the loops, for cases where the interrupted() is called and the thread is not in sleep().

Browser other questions tagged

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