《java并发编程实战》(二)

看《java并发编程实战》一书时,在33-34页中,对里面的例子不是很理解,究竟该怎么理解“不要在构造过程中使this引用逸出”,后来在segmentfault中找到一个问题,看完才有点理解。现作记录:

原文出处:https://segmentfault.com/q/1010000007900854/a-1020000018104804

才发现,书中给出的实例代码只是片段而已,并不完整。看书时可以到http://jcip.net/listings去找对应篇章的完整代码,不然只看书中的代码片段是很难理解文中想表达的意思的。

比如书中程序清单3-7的完整代码如下:

package net.jcip.examples;

/**
 * ThisEscape
 * <p/>
 * Implicitly allowing the this reference to escape
 *
 * @author Brian Goetz and Tim Peierls
 */
public class ThisEscape {
    public ThisEscape(EventSource source) {
        source.registerListener(new EventListener() {
            public void onEvent(Event e) {
                doSomething(e);
            }
        });
    }

    void doSomething(Event e) {
    }


    interface EventSource {
        void registerListener(EventListener e);
    }

    interface EventListener {
        void onEvent(Event e);
    }

    interface Event {
    }
}

但是在书中只给出了如下的一部分而已

public ThisEscape(EventSource source) {
        source.registerListener(new EventListener() {
            public void onEvent(Event e) {
                doSomething(e);
            }
        });
    }

顺便把开篇里面的那个讨论中的一个回答贴一下

讨论中还有剩余的两个回答,可以去看看,加深理解

猜你喜欢

转载自www.cnblogs.com/Guhongying/p/12821249.html
今日推荐