1.finalize()的特殊用法:
class Book{
boolean checkedOut=false;
Book(boolean checkOut){
checkedOut=checkOut;
}
/**
*
* @Title: ckeckIn
* @Description: TODO 签入
* @param 参数说明
* @return void 返回类型
* @throws
*/
void checkIn(){
checkedOut=false;
}
@Override
protected void finalize() throws Throwable {
if(checkedOut) {
System.out.println("Error:有一本书未被签入!");
}
// super.finalize();
}
}
public class haha {
public static void main(String[] args) {
Book book=new Book(true);
book.checkIn();
new Book(true);
System.gc();
}
}
|
本例的终结条件是:所有的BOOK对象再被当做垃圾回收前都应该被签入(checkIn),但是在main方法中,由于程序员的错误,有一本书没有被签入。
我们就可以用finalize进行检验,如果没有被check in,就报错提醒!
使用finalize方法进行对象的复活:
public
class
Haha {
public
static
Haha
haha
=
null
;
public
static
void
main(String[]
args
)
throws
InterruptedException {
haha
=
new
Haha();
haha
=
null
;
System.
gc
();
Thread.
sleep
(500);
if
(
haha
!=
null
) {
System.
out
.println(
"I alive!哈哈哈哈"
);
}
else
{
System.
out
.println(
"I dead! Over!"
);
}
}
@Override
protected
void
finalize()
throws
Throwable {
//
TODO
Auto-generated method stub
super
.finalize();
haha
=
this
;
}
}
|