- public class HashMapThread {
- public static final HashMap<String,String> firstHashMap = new HashMap<String, String>();
- public static void main(String[] args) throws Exception {
- //线程1
- Thread t1 = new Thread(){
- public void run(){
- for(int i=0;i<25;i++){
- firstHashMap.put(String.valueOf(i), String.valueOf(i));
- }
- }
- };
- Thread t2 = new Thread(){
- public void run(){
- for(int j=25;j<50;j++){
- firstHashMap.put(String.valueOf(j), String.valueOf(j));
- }
- }
- };
- t1.start();
- t2.start();
- Thread.currentThread().sleep(1000);//注线程休息1秒,以便于t1,t2链各个线程填充firstHashMap完成
- //如果key和value不同,说明两个线程在同步的时候HashMap出现了异常
- for(int l = 0;l<50;l++){
- if(!String.valueOf(l).equals(firstHashMap.get(String.valueOf(l)))){
- System.out.println(String.valueOf(l)+":"+firstHashMap.get(String.valueOf(l)));
- }
- }
- }
- }
- 自己验证之后的结果是:
- 2:null
- 5:null
- 7:null
- 9:null
复制代码 |
|