How to ensure finalize() is always called (Thinking in Java exercise)

前端 未结 5 847
情深已故
情深已故 2020-12-10 03:51

I\'m slowly working through Bruce Eckel\'s Thinking in Java 4th edition, and the following problem has me stumped:

Create a class with a fina

5条回答
  •  一向
    一向 (楼主)
    2020-12-10 04:05

    run new constructor() and System.gc() more than twice.

    public class Horse {
        boolean inStable;
        Horse(boolean in){
            inStable = in;
        }   
        public void finalize(){
            if (!inStable) System.out.print("Error: A horse is out of its stable!");
        }
    }
    public class MainWindow {
        public static void main(String[] args) {
            for (int i=0;i<100;i++){
                Horse h = new Horse(false);
                h = new Horse(true);
                System.gc();
            }
        }
    }  
    

提交回复
热议问题