【发布时间】:2013-01-22 21:30:29
【问题描述】:
查看 JLabel 的源代码,我担心文本字段的可见性。 我提取了基本部分来设置文本字段并检索 oldValue。 在我看来,如果 String 文本字段未声明为 volatile,则可见性处于危险之中,因为 firePropertyChange 可能看不到从之前由另一个线程保存的文本字段中检索到的 oldValue。 我是对的,还是我错过了什么? 请注意这里不是讨论 SwingUtility。
public class JLabel extends JComponent implements SwingConstants, Accessible {
...
private String text = ""; // "" rather than null, for BeanBox
...
public void setText(String text) {
String oldAccessibleName = null;
if (accessibleContext != null) {
oldAccessibleName = accessibleContext.getAccessibleName();
}
String oldValue = this.text;
this.text = text;
firePropertyChange("text", oldValue, text);
...
非常感谢。
【问题讨论】:
-
Please note this is not to discuss about SwingUtility.,没错,我同意了,为了更好的帮助,请尽快发布一个 SSCCE 简短的、可运行的、可编译的,仅JFrame和一个JLabel -
JLabel setText() 方法据说是线程安全的谁/什么说这样的废话?
-
对不起,JTextPane 似乎有一个线程安全的 setText() 方法,但是它没有像 JLabel 那样查找的文本字段。但总的来说,上面的代码 sn-p 并不能确保跨多个线程的可见性,对吧?这将回答我的问题。
-
我在 JDK7 文档中没有看到任何表明 JTextPane#setText 是线程安全的内容
-
嗯,JTextPane 从 JEditorPane 继承 setText。对于 JDK6,文档说它是线程安全的。对于 JDK 7,它说不是。
标签: java multithreading swing visibility volatile