我在实践中阅读 Java 并发,下面的示例来自于此。我的问题是这个引用转义是什么意思?会有什么问题?. this 引用如何从 doSomething(e) 中逃脱。
public class ThisEscape {
public ThisEscape(EventSource source) {
source.registerListener(
new EventListener() {
public void onEvent(Event e) {
doSomething(e);
}
}
);
}
}
这如何解决问题
public class SafeListener {
private final EventListener listener;
private SafeListener() {
listener = new EventListener() {
public void onEvent(Event e) {
doSomething(e);
}
};
}
public static SafeListener newInstance(EventSource source) {
SafeListener safe = new SafeListener();
source.registerListener(safe.listener);
return safe;
}
}
编辑 :
我已经尝试了以下示例
public class Escape {
public Escape( Printer printer ){
printer.print(new Escaper(){
@Override
public void parentData(){
theCulprit1(Escape.this);
}
public String name = "shal";
@Override
public void theCulprit(){
System.out.println( this.name );
System.out.println( Escape.this.age );
}
});
canAccess();
}
public void canAccess(){
this.age = "25";
}
public String age = "62";
@SuppressWarnings("unused")
public static void main(String args[]){
Escape escape = new Escape(new Printer());
}
}
class Printer{
public void print(Escaper escaper){
escaper.theCulprit();
escaper.parentData();
}
}
class Escaper{
public void parentData(){
}
public void theCulprit(){
}
public void theCulprit1(Escape escape){
System.out.println(escape.age);
}
}
由于逃生对象的构造不完整 这输出 shal 62 62
当我像这样更改我的代码时
public class Escape {
private final Escaper escaper;
private Escape( ){
escaper = new Escaper(){
@Override
public void parentData(){
theCulprit1(Escape.this);
}
public String name = "shal";
public void theCulprit(){
System.out.println( name );
System.out.println( age );
}
};
canAccess();
}
public void canAccess(){
age = "25";
}
public String age = "62";
public static Escape newInstance( Printer printer){
Escape escape = new Escape();
printer.print(escape.escaper);
return escape;
}
@SuppressWarnings("unused")
public static void main(String args[]){
Escape.newInstance(new Printer());
}
}
就像这里一样。它输出 shal 25 25
我对吗 ?还有是否对操作进行了重新排序,因为在第一个示例中,年龄被初始化为 62。即使在我的第二个示例中没有使逃逸者字段成为 final,它也可以工作!