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(); } }
why is the Internet() unnecessary?
– rrr
Because when the
InterruptedExceptionthread is already stopped. There is no need to stop it again. Simplyinterrupt()calls withinactionPerformed(), which are the ones that cause the launch ofInterruptedException.– Piovezan
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 theinterrupted()is called and the thread is not insleep().– Piovezan