Java杀死或终止线程 [英] Java kill or terminate a thread
问题描述
大家好:
基本上,当用户按下终止按钮时,我需要终止或停止运行线程。该线程遍历arraylist并在JTextArea上显示每个事件。要求是当用户按下终止按钮时,我需要终止正在运行的线程,同时将新的终止事件添加到数组列表中,并使其再次运行以打印编程终止。以下代码类型有效,但在控制台中出现了java.util.ConcurrentModificationException。有人可以帮忙吗?
Hi all: Basically I need to kill or stop a thread running when user press a Terminate button. This thread loop through a arraylist and display each event on JTextArea. The requirement is when user press the Terminate button, I need to terminate the running thread and at the same time ADD a new "Terminating" event to the arraylist and let it run again to print "Programing terminating". The following code kind of "works", but I got a java.util.ConcurrentModificationException in the console. Anyone 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();
}
}
推荐答案
似乎您在迭代列表时正在修改列表(清除列表然后添加新的 Terminate
事件)。这就是为什么您得到 ConcurrentModificationException
的原因。
It looks like you are modifying the list (clearing it then adding a new Terminate
event) while iterating on it. That's why you get the ConcurrentModificationException
.
我建议您简单地使用终止符()
方法,并调用它以停止打印列表中的事件,然后在不使用列表的情况下打印新的 Terminate
事件。
I would advise you to simply have a terminate()
method in your thread object, and call it to stop printing event the list THEN print the new Terminate
event, without using the list.
这篇关于Java杀死或终止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!