| 
 
| 若能很好了解决方法,有奖励哟....{:soso_e113:}复制代码 import java.util.Collection;
        import java.util.HashMap;
        import java.util.Iterator;
        import java.util.Map;
        import java.util.Random;
        import java.util.Set;
        import java.util.concurrent.locks.ReentrantReadWriteLock;
        
        public class CacheItem {
        
                private static Map<String ,Object> cache = new HashMap<String ,Object>();
                private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
                public static Object getObject(String key,Object target){
                        readWriteLock.readLock().lock();
                        Object polixy = null;        
                        try{
                                polixy = cache.get(key);
                                if(polixy==null){
                                        readWriteLock.readLock().unlock();        
                                        readWriteLock.writeLock().lock();
                                        try{
                                        if(polixy==null){
                                          polixy = target;
                                          cache.put(key, polixy);
                                        }        
                                 }
                                  finally{
                                        readWriteLock.writeLock().unlock();
                                  }
                           }
                                readWriteLock.readLock().lock();                
                        }
                        finally{
                                readWriteLock.readLock().unlock();
                        }        
                 return polixy;                        
          }
                
                public static void main(String[] args) {
                        
                  for(int i=0;i<10;i++){
                         final int count = i; 
                         new Thread(new Runnable(){
        
                                @Override
                                public void run() {
                                         System.out.println(Thread.currentThread().getName()+" ::: "+count+" ::: "+CacheItem.getObject(String.valueOf(count), new Random().nextInt(1000)));        
                                }
                                 
                         }).start();  
                  }
                                                            
                         for(Map.Entry<String, Object>  itdemo : cache.entrySet()){
                                 System.out.println("key="+itdemo.getKey()+","+"value="+itdemo.getValue());  // 结果不是预期想要了,要么少了几个element ,要么并发修改异常.....崩溃了
                         }
                         
                         System.out.println(cache.toString());
 
 
 | 
 |