JAVA的MAP.size()出现负数,在网上没找到任何资料,其实只是同步问题的一个例子,看代码就全明白了。
package test_prjmen;
import java.util.HashMap;
import java.util.Vector;
public class TEST_MAPNAG {
/**
* @param args
*/
public static void main(String[] args) {
final HashMap<String,String> map = new HashMap<String,String>();
final Vector<String> strs = new Vector<String> ();
new Thread(){
public void run(){
String name;
// for (int i=0;i<10;i++){
// name =”ABC”+i;
// map.put(”ABC”+i,”XYZ”);
// strs.add(name);
// }
while (true){
System.out.println(”<<SIZE>>”+map.size());
try {
sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
for (int i=0;i<100;i++){
new Thread(){
public void run(){
while (true){
synchronized(map){
String name = “ABC”+System.currentTimeMillis();
map.put(name,”XYZ”);
strs.add(name);
}
try {
sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
new Thread(){
public void run(){
while (true){
String str=null;
if (!strs.isEmpty())
str= strs.remove(0);
// synchronized(map){ //如果不加这句话,你就有机会获得负数的SIZE
map.remove(”XYZ”);
// try {
// sleep(1000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
map.remove(str);
// }
try {
sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
}
}
只要加上一个synchronized 就OK了。