当前位置: 移动技术网 > IT编程>开发语言>Java > Java并发编程this逃逸问题总结

Java并发编程this逃逸问题总结

2019年07月19日  | 移动技术网IT编程  | 我要评论

this逃逸是指在构造函数返回之前其他线程就持有该对象的引用. 调用尚未构造完全的对象的方法可能引发令人疑惑的错误, 因此应该避免this逃逸的发生.

this逃逸经常发生在构造函数中启动线程或注册监听器时, 如:

public class thisescape { 
  public thisescape() { 
    new thread(new escaperunnable()).start(); 
    // ... 
  } 
   
  private class escaperunnable implements runnable { 
    @override 
    public void run() { 
      // 通过thisescape.this就可以引用外围类对象, 但是此时外围类对象可能还没有构造完成, 即发生了外围类的this引用的逃逸 
    } 
  } 
} 

解决办法

public class thisescape { 
  private thread t; 
  public thisescape() { 
    t = new thread(new escaperunnable()); 
    // ... 
  } 
   
  public void init() { 
    t.start(); 
  } 
   
  private class escaperunnable implements runnable { 
    @override 
    public void run() { 
      // 通过thisescape.this就可以引用外围类对象, 此时可以保证外围类对象已经构造完成 
    } 
  } 
} 

以上就是小编本次整理的全部内容,感谢你对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网