【发布时间】:2014-07-24 11:02:37
【问题描述】:
我最近尝试了解 java.util.WeakHashMap。
但是当我使用 WeakReference 包装一个字符串时,WeakHash 并没有最终确定条目。
另请注意,我在主线程中清除 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();
}
}
【问题讨论】:
标签: java collections weakhashmap