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
     *///:~
     
     
  • 相关阅读:
    dpdk 连接错误
    strace 跟踪文件
    鲲鹏服务器 centos 升级gcc + 安装qemu
    centos 升级gcc
    undefined reference to `shm_open'
    Golang与C互用
    [ TIME ] Timed out waiting for device dev-ttyS0.device. [DEPEND] Dependency failed for Serial Getty on ttyS0.
    大型 Web 应用插件化架构探索
    网易游戏基于 Flink 的流式 ETL 建设
    基于WASM的无侵入式全链路A/B Test实践
  • 原文地址:https://www.cnblogs.com/lijingran/p/8997777.html
Copyright © 2011-2022 走看看