Java问题一:什么是this逃逸

来源:互联网 发布:每股收益的算法 编辑:程序博客网 时间:2024/06/01 08:40
  • 什么是this逃逸
    this逃逸是指构造函数返回之前其他线程持有该对象的引用,this逃逸经常发生在构造函数中启动线程或注册监听器。
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调用外围类对象的,但是测试外围累对象可能还没有构造完成,             * 所以会发生this逃逸现象             */            System.out.println(ThisEscape.this.value);        }    }}

正确方式应该如下:

public class FixThisEscape {    private String value = "";    private Thread thd;    public FixThisEscape() {        /**         * 构造函数中可以创建Thread对象,但是不要启动,另外使用start方法启动线程         */        thd = new Thread(new TestDemo());        this.value = "this escape";    }    public void start() {        thd.start();    }    public class TestDemo implements Runnable {        @Override        public void run() {            System.out.println(FixThisEscape.this.value);        }    }}
原创粉丝点击