I have a program where sequential drawing of the picture is performed - like animation.

//------------ public void paint (Graphics g){ g = (Graphics2D) g; if (p.dx==1&&!k){ k=true; ani.start(); // ani - это поток } } //--- public void run() { boolean l=false; while(l==false){ p.move(); try { ani.sleep(10); catch{//обработка исключения } } } 

Here, when you press the key, we start the stream, which every 10ms changes the image coordinates. But there is one problem. In this form, the thread will run only 1 time, and then the error will be thrown out. If you enter ani= new Thread(this) in the paint() method before starting the thread, then everything will work, but a lot of threads will be created, which will affect the speed of work accordingly.

How to stop it after the work of the thread and then, when necessary, start it with the .start() method?

  • one
    one thread object can be run only once. please read the books or manuals, this is written immediately in the chapter on flow conditions. - Viacheslav
  • oh how bad it turned out ((I just ran the program in NetBeans in debug mode, and he showed me that Thread-1 is running, then Thread-2, and so on. I felt scared on Thread-143. I thought that it creates a bunch streams that eat a lot) - whispeer

2 answers 2

The thread is executed 1 time, as written in the documentation:

It is never legal. Once it has completed execution.

That is why you throw an exception - obviously IllegalThreadStateException , which is just thrown when you try to restart the thread.

In general, you need to create a new Thread object each time.

Many threads are created because they do not stop at you, but the thread stops at the end of a cycle at run() - think about how you should stop it, that is, somewhere it should get l=true

    In the while loop, you need to do a check! Thread.isInterrupted (), and in the paint method, interrupt the current thread by calling interrupt () on it, and then wait for it to finish (). When the thread has stopped, create a new one and call start () on it. Something like this:

     public void paint(Graphics g) { g = (Graphics2D) g; if (p.dx == 1 && !k) { k = true; ani.interrupt(); ani.join(); ani=//создание нового потока ani.start(); // ani - это поток } } public void run() { while (!Thread.currentThread().isInterrupted()) { p.move(); try { ani.sleep(10); }catch{//обработка исключения } } } }