zoukankan      html  css  js  c++  java
  • java编程思想-第五章-某些练习题

    参考https://blog.csdn.net/caroline_wendy/article/details/46844651

    10&11

    finalize()被调用的条件

    Java1.6以下的条件:

    (1)类未被调用(置null)(2)调用System.gc()

    1.8的条件:

    (1)调用System.gc().(在调用了System.gc()之后,finalize()才被执行,也就是在执行最后一个 ‘}’时,finalize()才被执行)

    //: Main.java
    
    /**
     * 垃圾回收
     * 注意: Java环境1.6可以, 1.8不可以, 垃圾回收机制改变.
     */
    
    class Test {
        @Override
        protected void finalize(){
            System.out.println("finalize");
    //        super.finalize();
        }
    }
    
    class Main {
        public static void main(String[] args) {
            Test t = new Test();
            t = null; // 确保finalize()会被调用
            System.gc();
        }
    }
    /**
     * Output:
     finalize
     *///:~

    12

    清理对象时, 会调用finalize()函数, 并且会保留存储数据, 如T2;
    在清理对象时, 会入栈出栈, 先入后清理, 后入先清理.

    //: Main.java
    
    /**
     * 垃圾回收
     * 注意: Java环境1.6可以, 1.8不可以, 垃圾回收机制改变.
     */
    
    class Tank {
        boolean isFull = false;
        String name;
        Tank(String name) {
            this.name = name;
        }
        void setEmpty() {
            isFull = false;
        }
        void setFull() {
            isFull = true;
        }
    
        @Override
        protected void finalize(){
            if (!isFull) {
                System.out.println(name + ": 清理");
            }
    //        super.finalize();
        }
    }
    
    class Main {
        public static void main(String[] args) {
            Tank t1 = new Tank("T1");
            Tank t2 = new Tank("T2");
            Tank t3 = new Tank("T3");
            t1.setFull();
            t2.setEmpty();
            t1 = null;
            t2 = null;
            t3 = null;
            System.gc();
        }
    }
    /**
     * Output:
     T3: 清理
     T2: 清理
     *///:~

    20

    //: OtherMain.java
    
    /**
     * 测试main的可变参数形式
     * Created by wang on 15/7/30.
     */
    public class OtherMain {
        public static void main(String... args) {
            for (String s : args) {
                System.out.print(s + " ");
            }
            System.out.println();
        }
    }
    /**
     * Output:
     * haha ahah haah ahha
     *///:~
     
     
  • 相关阅读:
    获取N年,N月,N日后或者前的日期函数
    ABAP 上传图片
    SF 小技巧
    针式打印机问题
    ABAP 捕获回车键
    md04 取数函数
    根据选择屏幕创建12个月份
    php isset 的作用
    php 指针概念 指针引用
    php中global与$GLOBALS的用法及区别
  • 原文地址:https://www.cnblogs.com/lijingran/p/8997777.html
Copyright © 2011-2022 走看看