this逃逸

时间:2023-03-09 16:50:21
this逃逸

首先,什么是this逃逸?

this逃逸是指类构造函数在返回实例之前,线程便持有该对象的引用。

常发生于在构造函数中启动线程或注册监听器。

eg:

public class ThisEscape {
private String value = ""; public ThisEscape() {
new Thread(new TestDemo()).start();
this.value = "this escape";
} public class TestDemo implements Runnable {
@Override
public void run() {
/**
* 备注:这里通过ThisEscape.this可调用外围类(即ThisEscape是TestDemo的外围类)的对象,
        * 但此时外围类对象可能还没有构造完成,
* 所以会发生this逃逸现象
*/
System.out.println(ThisEscape.this.value);
}
}
}