我最近試圖理解java.util.WeakHashMap。爲什麼WeakReferenced對象不能被WeakHashMap去掉
但是,當我使用WeakReference來包裝一個字符串時,WeakHash沒有完成Entry。
另請注意,我正在清除主線程中的WeakReference,然後在線程方法內引用它。
執行時,while循環根本沒有中斷!
public class WeakHashMapTotorial
{
private static Map<String, String> map;
public static void main(String args[])
{
WeakReference<String> s = new WeakReference<String>("Maine");
map = new WeakHashMap<>();
map.put(s.get(), "Augusta");
Runnable runner = new Runnable()
{
public void run()
{
while (map.containsKey("Maine"))
{
try
{
Thread.sleep(1000);
} catch (InterruptedException ignored)
{}
System.out.println("Thread waiting");
System.gc();
}
}
};
Thread t = new Thread(runner);
t.start();
System.out.println("Main waiting");
try
{
t.join();
} catch (InterruptedException ignored)
{}
s.clear();
}
}
謝謝克里斯。我現在得到了缺失的位:) – Maas