Swing JTextArea多线程问题--InterruptedException [英] Swing JTextArea multithreading problem - InterruptedException
问题描述
我有一个简单的控制台应用程序,它在几个线程中运行计算(其中10-20个)。现在我正在尝试创建一个简单的GUI,允许我选择要处理的文件并打印来自所有线程的日志。
I have a simple console application that runs calculations in several threads (10-20 of them). Now I'm trying to create a simple GUI that allows me to select the file to process and prints logs from all threads.
所以,我用JTextArea创建了一个swing GUI对于我的日志和将信息记录到日志的方法:
So, I created a swing GUI with JTextArea for my log and a method to log information to the log:
public synchronized void log(String text) {
logArea.append(text);
logArea.append("\n");
if (logArea.getDocument().getLength() > 50000) {
try {
logArea.getDocument().remove(0,5000);
} catch (BadLocationException e) {
log.error("Can't clean log", e);
}
}
logArea.setCaretPosition(logArea.getDocument().getLength());
}
然而, setCaretPosition
方法有时在等待一些锁时死锁,而追加
有时会抛出InterruptedException。
However, the setCaretPosition
method sometimes deadlocks on waiting some lock, and append
sometimes throws InterruptedException.
Exception in thread "Thread-401" java.lang.Error: Interrupted attempt to aquire write lock
at javax.swing.text.AbstractDocument.writeLock(AbstractDocument.java:1334)
at javax.swing.text.AbstractDocument.insertString(AbstractDocument.java:687)
at javax.swing.text.PlainDocument.insertString(PlainDocument.java:114)
at javax.swing.JTextArea.append(JTextArea.java:470)
at lt.quarko.aquila.scripts.ui.ScriptSessionFrame.log(ScriptSessionFrame.java:215)
我是Swing的新手,所以我无法理解我在这里做错了什么?
I'm a total newbie in Swing, so I can not understand what am I doing wrong here?
提前致谢。
推荐答案
你不想要直接从另一个线程操纵Swing对象,你想要对它的事件队列进行操作 。
You don't want to manipulate Swing objects directly from another thread, you want to post manipulations to it's event queue.
这篇关于Swing JTextArea多线程问题--InterruptedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!