
对象在发布时,应确保可发布对象线程安全;防止不可发布对象被发布出去,破坏面向对象中的密封性。
public class ThisEscape {
final int a;
int b=0;
static ThisEscape obj;
public ThisEscape(){
a=1;
b=1;
obj=this;
}
public static void main(String[] args) {
/**
* 线程A:模拟构造器中this逃逸,将未构造完全对象引用抛出
*/
Thread threadA =new Thread(new Runnable() {
@Override
public void run() {
obj=new ThisEscape();
}
});
/**
* 线程B:读取对象引用,访问a/b变量
*/
Thread threadB=new Thread(new Runnable() {
@Override
public void run() {
ThisEscape objA = obj;
try {
System.out.println(objA.b);
}catch (NullPointerException e){
System.out.println("发生空指针错误:普通变量b未被初始化");
}
try {
System.out.println(objA.a);
} catch (NullPointerException e) {
System.out.println("发生空指针错误:final变量a未被初始化");
}
}
});
threadB.start();
}
}
线程A模拟this逃逸,但是不一定发生,而线程B发生this逃逸这是因为:
发生This逃逸一般会有两种情况:
public class EventHandle01 implements Runnable {
private Thread threadA=null;
public EventHandle01() {
threadA = new Thread(new EventHandle01());
}
public void initStart() {
threadA.start();
}
@Override
public void run() {
System.out.println("This is the run method");
}
}
static{
source.registerListener(
new EventListener() {
public void onEvent(Event e) {
doSomething(e);
}
}
);
var = 10;
}This逃逸一般发生在多线程中,引起This逃逸的问题是在多线程滥用引用。在多线程中,使用到引用的时候多加注意.
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。