java 匿名对象有引用,封闭对象的引用通过匿名类java进行转义

我在实践中阅读

Java并发性,下面的例子来自于此.我的问题是

这个参考逃脱是什么意思?会有什么问题? .这个引用是如何从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.

即使没有在我的第二个例子中进行自由竞技场决赛,它仍然有效!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值