实现一个简单的代理实现HashMap同步的功能如下运行结果:
package demo;
import java.util.HashMap;
public class Main {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//使用代理实现同步的Map
final SynchronizedMap<Integer, Integer> sm = new SynchronizedMap<Integer, Integer>(
new HashMap<Integer, Integer>());
//普通的Map
final HashMap<Integer, Integer> hs=new HashMap<Integer, Integer>();
for (int i = 0; i < 2000; i++) {
final int n = i;
new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hs.put(n, n);
sm.put(n, n);
}
}.start();
}
Thread.sleep(2000);
System.out.println("实现同步的map sm的长度="+sm.size()+"\n"+"未实现同步的map hs的长度="+hs.size());
}
}