I just learned java. weakreference is widely used in Android. It is mainly used in asynchronous mode and I don't quite understand it. I 'd like to test it with code segments:
Import java. Lang. Ref. phantomreference;
Import java. Lang. Ref. softreference;
Import java. Lang. Ref. weakreference;
Import java. Lang. Ref. reference;
Import java. Lang. Reflect. field;
Import java. Lang. thread;
Class thread1 extends thread {
Weakreference <string> m_str2weakref;
Thread1 (string Str ){
M_str2weakref = new weakreference <string> (STR );
System. Out. println ("111 str2weakref str2 =" + m_str2weakref.get ());
Start ();
}
Public void run (){
Try
{
Thread. Sleep (5001 );
} Catch (exception e ){}
System. Out. println ("222 str1weakref str2 =" + m_str2weakref.get (); // str2 has been recycled
}
}
Public Class re {
Public static void main (string [] ARGs) throws exception {
String str1 = new string ("str1 ");
String str2 = new string ("str2 ");
String str3 = new string ("str3 ");
String TMP;
Weakreference <string> str1weakref = new weakreference <string> (str1 );
Weakreference <string> str3weakref = new weakreference <string> (str3 );
// Softrefenrence <string> sr = new softreference <string> (ABC );
// Reference <Object> ref = new softreference <Object> (ABC );
Thread1 Th1 = new thread1 (str2 );
Str1 = NULL;
Str2 = NULL;
Str3 = NULL;
// Thread. currentthread (). Sleep (1000 );
System. Out. println ("111 str1weakref str1 =" + str1weakref. Get ());
System. Out. println ("111 str3weakref str3 =" + str3weakref. Get ());
System. Out. println ("start gc ");
TMP = str3weakref. Get (); // This Code indicates that str3 is not recycled,
System. GC ();
System. Out. println ("after GC ");
// Thread. currentthread (). Sleep (1000 );
System. Out. println ("222 str1weakref str1 =" + str1weakref. Get (); // str1 has been recycled
System. Out. println ("222 str3weakref str3 =" + str3weakref. Get (); // str3 is not recycled
System. Out. println ("main end ");
}
}
Output result of the above Code:
111 str2weakref str2 = str2
111 str1weakref str1 = str1
111 str3weakref str3 = str3
Start GC
After GC
222 str1weakref str1 = NULL
222 str3weakref str3 = str3
Main end
222 str1weakref str2 = NULL