Start a thread again

2

I have an event on the start button, every time I load, 3 threads are started that start counting from 30 to 0, which reaches 1 to 0 wins. But however I reload the start button a few times and the count starts at 30 and does everything the same, if you continue to press the start button a second or two times it will fail and stop running the thread. My question is: I start three threads when I press the start button but to redo this in the same frame do I have to kill the threads or interrupt them?

c1, c2, c3 are Horse objects.

  • Horse Racing 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 from 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();
    }
    } 
    
asked by anonymous 14.10.2016 / 01:06

1 answer

2

Yes, you need to end the threads. More than this, you must declare your Horse Instances within actionPerformed() , so that each new thread is created and executed:

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 catch is unnecessary.

    
14.10.2016 / 03:03