1、代码取消强引用后,gc回收对象
public static void main ( String [ ] args) { Object obj = new Object ( ) ; WeakReference < Object > weakRef = new WeakReference < > ( obj) ; System . out. println ( weakRef. get ( ) ) ; obj = null ; System . gc ( ) ; System . out. println ( weakRef. get ( ) ) ; if ( weakRef. get ( ) == null ) { System . out. println ( "对象已经被回收" ) ; } else { System . out. println ( "对象仍然存在" ) ; } }
2、不取消强引用,gc无法回收
public static void main ( String [ ] args) { Object obj = new Object ( ) ; WeakReference < Object > weakRef = new WeakReference < > ( obj) ; System . out. println ( weakRef. get ( ) ) ; System . gc ( ) ; System . out. println ( weakRef. get ( ) ) ; if ( weakRef. get ( ) == null ) { System . out. println ( "对象已经被回收" ) ; } else { System . out. println ( "对象仍然存在" ) ; } }
3、总结,将对象设置为null可结束强引用,保证能够被回收。