import java.util.HashMap;
import java.util.Map;
public class MainTest
{
static Map<String, Integer> map = new HashMap();
public static void incr()
{
map.merge("counter", 1, Integer::sum);
}
public static void decr()
{
map.merge("counter", -1, Integer::sum);
}
public static void main(String[] args) throws Exception
{
map.put("counter", 0);
for (int i = 0; i < 10000; i++)
{
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
incr();
}
});
t1.join();
t1.start();
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
decr();
}
});
t2.join();
t2.start();
}
System.out.println(map);
}
}
在运行主方法时,结果为
{counter=-2}
。为什么不是0呢?
HashMap
不是线程安全的,所以HashMap
上的任何方法都不是线程安全的。 - Boris the Spider