|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
class
Island{
public
Island brother;
String name;
public
Island(){
}
public
Island(String name){
this
.name = name;
}
public
void
finalize(){
System.out.println(
this
.name +
"对象成为垃圾,被收集"
);
}
public
void
testIsland(){
Island i1 =
new
Island(
"孤岛中的 O1"
);
Island i2 =
new
Island(
"孤岛中的 O2"
);
Island i3 =
new
Island(
"孤岛中的 O3"
);
i1.brother = i2;
i2.brother = i3;
i3.brother = i1;
i1 =
null
;
i2 =
null
;
i3 =
null
;
// 这样 三个对象循环指向 但他们形成了孤岛 所以已经成为垃圾
System.gc();
//可以看到 三个对象很快被收集,但程序过了10s才结束
try
{
Thread.sleep(
10000
);
}
catch
(Exception e){
e.printStackTrace();
}
}
}
public
class
Test{
public
static
void
main(String[] args){
new
Island().testIsland();
}
}
|
GC如何知道对象没被引用(孤岛例子)
最新推荐文章于 2025-08-10 17:27:43 发布
本文深入探讨了Java虚拟机中垃圾回收的基本原理,介绍了两种主要的垃圾回收算法——停止-复制和标记-清除,并通过示例代码验证了孤立对象的回收过程。
93

被折叠的 条评论
为什么被折叠?



