请写一个person类,在测试类中创建2个对象,将2个对象变成垃圾对象,并进行回收,要求回收时提示:“垃圾对象被回收!”。
时间: 2024-09-25 22:18:21 浏览: 50
在Java中,当一个对象不再有任何引用指向它时,垃圾收集器就会自动回收这个对象。为了模拟这种场景,我们可以创建一个`Person`类,然后在一个测试类中创建两个对象,但在适当的时候断开它们的引用,使它们成为垃圾对象。
首先,我们定义一个简单的`Person`类:
```java
public class Person {
private String name;
// 构造函数
public Person(String name) {
this.name = name;
}
// 重写toString()方法用于打印对象信息
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
```
接着,在测试类中,我们将创建、使用并释放这两个对象:
```java
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
public class GarbageCollectionTest {
public static void main(String[] args) {
// 创建一个 ReferenceQueue 对象来接收垃圾对象的引用
ReferenceQueue<Person> queue = new ReferenceQueue<>();
// 创建两个Person对象
Person person1 = new Person("Alice");
Person person2 = new Person("Bob");
System.out.println("Person 1: " + person1);
System.out.println("Person 2: " + person2);
// 将对象放入queue,使其成为弱引用
WeakReference<Person> weakRef1 = new WeakReference<>(person1, queue);
WeakReference<Person> weakRef2 = new WeakReference<>(person2, queue);
// 引用已经断开,这里person1和person2被视为垃圾
person1 = null;
person2 = null;
// 等待垃圾对象被回收
while (true) {
try {
// 如果队列中有可用的垃圾对象,则获取并打印消息
if (queue.poll() != null) {
System.out.println("Garbage object was collected!");
break;
} else {
Thread.sleep(100); // 暂停一段时间检查垃圾回收
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
在这个例子中,我们使用了`WeakReference`,这是一种特殊的引用类型,不会阻止垃圾收集器回收对象。当没有强引用指向一个弱引用的对象时,垃圾收集器会在下次循环时将其回收,因此你会看到类似"Garbage object was collected!"的消息。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)