我有一些代码可以进行一些初始化(包括制作一个 JTextArea 对象),启动三个独立的线程,然后这些线程尝试更新 JTextArea (即 append()),但它根本不起作用。 JTextArea 上没有显示任何内容(但是,在初始化期间,我会在其上打印一些测试行,这样可以正常工作)。这是怎么回事?我怎样才能解决这个问题?此外,每次必须更新 JTextArea 时,每个线程都会休眠一段时间。
I have some code that does some initialization (including making a JTextArea object), starts three separate threads, and then these threads try to update the JTextArea (i.e. append() to it), but its not working at all. Nothing shows up on the JTextArea (however, during the initialization, I print some test lines onto it, and that works fine). What's going on? How can I fix this? Also, each of those threads sleeps a random amount of time every time it has to update the JTextArea.
抱歉我没有提供任何代码,它全部分布在几个文件中。
Sorry I haven't provided any code, its all spread out over several files.
推荐答案虽然我相信API已声明JTextArea #append(...)是线程安全的,我听说过它的问题,并建议只在EDT上调用它。这方面的典型示例是使用SwingWorker并通过调用publish附加到流程方法中的JTextArea。
Although I believe the API has stated that JTextArea#append(...) is thread safe, I've heard of problems with it and would recommend that this only be called on the EDT. The classic example of this is to use a SwingWorker and append to the JTextArea in the process method by calling publish.
对我来说,如果没有代码,很难向你提出任何具体的建议。我不得不怀疑你是否让EDT在你的代码中的某个地方睡觉。
For me, it'll be hard to make any specific suggestions to you though without code. I do have to wonder though if you're putting the EDT to sleep somewhere in your code.
编辑:根据你的评论查看本教程: Swing中的并发
as per your comment check out this tutorial: Concurrency in Swing
编辑2:根据 Tim Perry 的评论,损失线程安全及其背后的原因已发布在此Java错误和这与代码行有关,其中文本被添加到JTextArea的文档中:
Edit 2: as per comment by Tim Perry, loss of thread safety and the reasoning behind this has been posted in this Java bug and which has to do with this line of code where text is added to the JTextArea's Document:
doc.insertString(doc.getLength(), str, null);该行分解为两行:
问题是如果文档出现问题, doc,第1行和第2行之间的更改,尤其是文档长度。
The issue is that a problem can occur if the Document, doc, changes between lines 1 and 2, especially the Document length.
更多推荐
JTextArea线程安全吗?
发布评论