Swing JTextArea多线程问题--InterruptedException

bez*_*max 6 java swing multithreading

我有一个简单的控制台应用程序,在几个线程(其中10-20个)中运行计算.现在我正在尝试创建一个简单的GUI,允许我选择要处理的文件并打印来自所有线程的日志.

因此,我使用JTextArea为我的日志创建了一个swing GUI,并将信息记录到日志中:

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());
}
Run Code Online (Sandbox Code Playgroud)

但是,该setCaretPosition方法有时会在等待某些锁时死锁,append有时会抛出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)
Run Code Online (Sandbox Code Playgroud)

我是Swing的新手,所以我无法理解我在这里做错了什么?

提前致谢.

Mud*_*Mud 5

您不希望直接从另一个线程操作Swing对象,您希望将操作发布到它的事件队列.