JTextArea线程安全吗?

编程入门 行业动态 更新时间:2024-10-23 20:21:19
本文介绍了JTextArea线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些代码可以进行一些初始化(包括制作一个 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);

该行分解为两行:

  • int len = doc.getLength();
  • doc.insertString (len,str,null);
  • int len=doc.getLength();
  • doc.insertString(len,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线程安全吗?

    本文发布于:2023-11-25 18:57:08,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1630942.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:线程   JTextArea

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!