【发布时间】:2012-09-26 00:18:52
【问题描述】:
我知道这是一个愚蠢的问题,但不知道如何解决这个问题,我以前没有太多使用线程的经验。
下面应该首先创建一个计时器,它将每 10 秒执行一次命令 output.write(mylist),它将简单地输出 mylist 的内容。
其次,它循环遍历我拥有的大约 3 个列表,并为每个列表创建一个线程,该线程将继续循环获取列表中的下一个单词。 请注意:这是精简版,并不完整,因此请不要评论数组列表/列表,而是评论错误本身。
当它尝试执行output.write() 时,经常发生并发修改异常,但并非一直发生。我猜这是因为其他线程之一当前正在将某些内容保存到mylist?我该如何解决这个问题?
Runnable timer = new Runnable() {
public void run() {
try {
while (true) {
Thread.sleep(10000);
output.write(mylist);
}
} catch (InterruptedException iex) {}
}
};
Thread timerThread = new Thread(timer);
timerThread.start();
for (final ValueList item : list) {
Runnable r = new Runnable() {
public void run() {
try {
while (true) {
char curr = item.getNext();
mylist.addWord(curr);
}
} catch (InterruptedException iex) {}
}
};
Thread thr = new Thread(r);
thr.start();
}
}
【问题讨论】:
-
output.write(mylist);是做什么的?我认为您缺少那里的同步步骤。考虑发布代码的相关部分,如果不是 SSCCE 突出您的问题。
标签: java multithreading exception concurrency