【发布时间】:2012-07-02 08:19:21
【问题描述】:
阅读了 Brain Goetz 关于安全构造技术的优秀文章this,我对清单 5 中给出的评论感到困惑。这是代码 sn-p:
public class Safe {
private Object me;
private Set set = new HashSet();
private Thread thread;
public Safe() {
// Safe because "me" is not visible from any other thread
me = this;
// Safe because "set" is not visible from any other thread
set.add(this);
// Safe because MyThread won't start until construction is complete
// and the constructor doesn't publish the reference
thread = new MyThread(this);
}
public void start() {
thread.start();
}
private class MyThread(Object o) {
private Object theObject;
public MyThread(Object o) {
this.theObject = o;
}
...
}
}
他为什么这么说me? // Safe because "me" is not visible from any other thread。两个线程不能同时访问实例变量me吗?
【问题讨论】:
-
我是私有的,为什么线程可以访问它?
标签: java concurrency synchronization this java.util.concurrent