zoukankan      html  css  js  c++  java
  • this引用逸出demo

    在看《Java 并发编程实践》时,有以下这个例子,说下边的this会逸出,说的太模糊,不理解。

    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 {
      }
    }
    

    于是,直降做了下demo:
    public class demo_02_ThisEscape {

        public static void main(String[] arge) {
            new ThisEscape(new ThisEscape.EventSource(){
                @Override
                public void registerListener(ThisEscape.EventListener e) {
                    System.out.println(e);
                    // 结果: java_thread.ThisEscape$1@470e2030
                }
            });
        	num = 100;
        }
    
    }
    class ThisEscape {
        int num = 0;
        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 {
        }
    }
    

    只用代码和输出还是不好理解,但是如果debug状态
    可以看到线程状态里,有包含ThisEscape的进程,同时,查看内部registerListener的参数ThisEscape.EventListener e的,可以看到ThisEscape的内部对象num。但实际上,这个时候还在ThisEscape的构造内部,ThisEscape实例化没有完成,num还是0的状态。
    构造和线程可能冲突。

    这大概就是this逸出吧。

  • 相关阅读:
    hdu1814 Peaceful Commission 2-SAT
    上传下载文件
    文件下载类
    文件操作类
    MD5加密帮助类
    加密解密类
    发送邮件函数
    DataTable 分页
    服务器缓存帮助类
    Cookie帮助类
  • 原文地址:https://www.cnblogs.com/changfanchangle/p/8884694.html
Copyright © 2011-2022 走看看