美文网首页
使用finalize让对象涅槃重生

使用finalize让对象涅槃重生

作者: 勤劳的杯子 | 来源:发表于2019-07-08 07:14 被阅读0次

    详情参见代码:

    package com.imooc.web;
    import sun.misc.GC;
    
    import javax.sound.midi.Track;
    import java.awt.print.Book;
    
    /**
     * Copyright (C), 2002-2019
     * FileName: TerminationCondition
     * <p>
     * Description:
     *
     * @author 如果这段代码非常棒就是梁子松写的
     * 如果这代码挺差劲那么我也不知道是谁写的
     * @version 1.0.0
     * @create 19-7-6 下午10:07
     */
    
    public class TerminationCondition {
    
        private static TerminationCondition book = null;
    
        boolean aBoolean;
    
        public TerminationCondition(boolean aBoolean) {
            this.aBoolean = aBoolean;
        }
    
        public static void main(String[] args) throws InterruptedException {
            //初始化
            book = new TerminationCondition(true);
            //取消引用
            book = null;
            //清理
            System.gc();
            //确保被清理
            Thread.sleep(500);
            //因为有finalize方法所以对象会重生
            if (null != book) { //此时对象应该处于(reachable, finalized)状态
                System.out.println("Yes , I am still alive");
            } else {
                System.out.println("No , I am dead");
            }
            //再次取消引用
            book = null;
            //调用gc
            System.gc();
            //确保被清理
            Thread.sleep(500);
            //因为之前已经调用过finalize方法了所以对象已经被清理
            if (null != book) {
                System.out.println("Yes , I am still alive");
            } else {
                System.out.println("No , I am dead");
            }
        }
    
        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            System.out.println("execute method finalize()");
            book = this;
        }
    }
    

    输出

    execute method finalize()
    Yes , I am still alive
    No , I am dead
    

    相关文章

      网友评论

          本文标题:使用finalize让对象涅槃重生

          本文链接:https://www.haomeiwen.com/subject/kjoghctx.html