Java kills or terminates a thread

Hi everyone: Basically, I need to kill or stop the thread when the user clicks the "Finish" button. This thread goes through the arraylist and displays each event in JTextArea. The requirement is that when the user clicks the “Finish” button, I need to terminate the thread that is running and at the same time add a new “Stop” event to the arraylist and run it again to print “Programming Complete”. The following code "works", but I got java.util.ConcurrentModificationException in the console. Who can help?

public void startEvents()
    {
        terminate = false;
        worker = new Thread(new Runnable()
        {
            public void run()
            {
                Iterator<Event> it = eventList.iterator();

                while (it.hasNext())
                {
                    waitWhileSuspended();
                    terminatEvents();
                    Event ev = it.next();
                    try
                    {
                        Thread.sleep(ev.getDelayTime());
                    } catch (InterruptedException e1)
                    {
                        e1.printStackTrace();
                    }
                    jTextArea.append(ev.toString() + "\n");
                    it.remove();
                }
                jbStart.setEnabled(true);
                jmiStart.setEnabled(true);
                jbRestart.setEnabled(true);
                jmiRestart.setEnabled(true);
            }
        });
        worker.start();
    }
public void terminatEvents()
    {
        while(terminate)
        {
            Thread.yield();
            eventList.clear();
            eventList.add(new Terminate(delayTime));
            startEvents();

        }
    }
+3
source share
5 answers

, . undefined, . java.util.concurrent , .

+1

, ( , Terminate), . ConcurrentModificationException.

terminate() , THEN. Terminate, .

+1

- volatile boolean flag, , terminate. , , while (!terminated && ...). , , - , , terminateEvent, , ( , , ). , terminateEvent ( , volatile, , ).

, , . (LinkedBlockingQueue - ), , , . , ( instanceof - getEventClass()), , .

, , Thread.sleep() , , waitWhileSuspended() ( , , ), () InterruptedException . , , , Thread.sleep() , , .

0

,

public void run() {
  while (!isInterrupted()) {
    // actual working code goes here
  }
} // end of life for this thread

(), .

0

Source: https://habr.com/ru/post/1780904/


All Articles