哪种Swing组件方法是线程安全的?

Joo*_*kka 19 java swing thread-safety

根据Swing教程:

一些Swing组件方法在API规范中标记为"线程安全"; 这些可以从任何线程安全地调用.必须从事件派发线程调用所有其他Swing组件方法.忽略此规则的程序可能在大多数情况下正常运行,但会遇到难以重现的不可预测的错误.

但是这些标记为"线程安全"的Swing组件方法是什么?实际上有吗?


更新/赏金:

是否有完整的线程安全摆动方法列表?(线程安全的Swing方法似乎很少见,所以这样的列表不能太长......)

Bal*_*usC 18

谷歌告诉我,至少那些是线程安全的.以下是链接再次破坏的情况概述:


  • JTextPane
    • replaceSelection()
    • insertComponent()
    • insertIcon()
    • setLogicalStyle()
    • setCharacterAttributes()
    • setParagraphAttributes()





  • StyleContext
    • addAttribute()
    • addAttributes()
    • removeAttribute()
    • removeAttributes()
    • reclaim()



  • 别客气.无论如何,这是一个有用的链接:http://www.googleguide.com/using_advanced_operators.html (2认同)

bgu*_*uiz 7

但是这些标记为"线程安全"的Swing组件方法是什么?

大多数Swing组件的方法都不是线程安全的.但有些人是.要找出哪些,你别无选择,只能仔细阅读目标组件的javadoc.精心构建的谷歌搜索可能会加快这一过程.

实际上有吗?

是的确有.一般来说,如果您正在使用Swing组件,则可能需要调用线程安全和非线程安全的方法.由于大多数方法都是非线程安全的,因此我更倾向于谨慎行事,并且无论如何都要以线程安全的方式对它们执行所有操作.

HTH


不详尽的清单.

DefaultStyledDocument:

  • protected void insert(int offset,DefaultStyledDocument.ElementSpec [] data)抛出BadLocationException
  • public void setLogicalStyle(int pos,Style s)
  • public void setCharacterAttributes(int offset,int length,AttributeSet s,boolean replace)
  • public void setParagraphAttributes(int offset,int length,AttributeSet s,boolean replace)

javax.swing.text.AbstractDocument中:

  • public void render(Runnable r)
  • public void remove(int offs,int len)抛出BadLocationException
  • public void insertString(int offs,String str,AttributeSet a)抛出BadLocationException
  • public Position createPosition(int offs)抛出BadLocationException

javax.swing.undo.UndoManager:
类是线程安全的

  • @BalusC没有!考虑一下这个事实,在你得出结论之前输入答案需要几分钟. (3认同)

Sha*_*der 5

对于带有javadocs和src文件中的注释的类列表,"is thread safe"返回以下内容

JEditorPane
JTextArea
AbstractDocument
DefaultCaret
DefaultStyledDocument
JTextComponent    
PlainDocument
StyleContext    
HTMLDocument
UndoManager
Run Code Online (Sandbox Code Playgroud)

这并不是说在src中有其他记录或未记录的线程安全的.

它让我觉得这是一个相当奇怪的问题,但我认为大多数组件都不是线程安全的,因为Swing是一个单线程模型,并且所有更新都需要在事件调度程序线程上进行,这很容易做到.