在HashMap中使用线程对象作为键

时间:2018-05-27 15:04:35

标签: java multithreading hashmap

我正在读这个: http://tutorials.jenkov.com/java-concurrency/read-write-locks.html

在本教程中,为了编写重入读锁定,使用了以下代码

    public class ReadWriteLock{

      private Map<Thread, Integer> readingThreads =
          new HashMap<Thread, Integer>();

      private int writers        = 0;
      private int writeRequests  = 0;

      public synchronized void lockRead() throws InterruptedException{
        Thread callingThread = Thread.currentThread();
        while(! canGrantReadAccess(callingThread)){
          wait();                                                                   
        }

        readingThreads.put(callingThread,
           (getAccessCount(callingThread) + 1));
      }


      public synchronized void unlockRead(){
        Thread callingThread = Thread.currentThread();
        int accessCount = getAccessCount(callingThread);
        if(accessCount == 1){ readingThreads.remove(callingThread); }
        else { readingThreads.put(callingThread, (accessCount -1)); }
        notifyAll();
      }


      private boolean canGrantReadAccess(Thread callingThread){
        if(writers > 0)            return false;
        if(isReader(callingThread) return true;
        if(writeRequests > 0)      return false;
        return true;
      }

      private int getReadAccessCount(Thread callingThread){
        Integer accessCount = readingThreads.get(callingThread);
        if(accessCount == null) return 0;
        return accessCount.intValue();
      }

      private boolean isReader(Thread callingThread){
        return readingThreads.get(callingThread) != null;
      }

    }

所以我有疑问,我可以像这样使用hashmap吗

  private Map<Thread, Integer> readingThreads =
      new HashMap<Thread, Integer>();

我检查了Thread类代码,检查它是否覆盖了equals和hashcode 并发现它没有。 所以它将是defaut equals和hashcode。 所以所有人都会指向相同的桶?

任何人都可以帮助我了解它将如何映射到存储桶。 另外,程序员需要使用线程对象作为hashmap的关键字吗?

1 个答案:

答案 0 :(得分:2)

  

所以所有人都指向相同的桶?

没有。在java中,每个类(包括Thread)都隐含地从Object类扩展。从equals类扩展的hashCodeObject方法足以使Thread个对象分布在不同的存储区中。

请参阅Object.equals的文档:

  

类Object的equals方法实现最具辨别力   对象可能的等价关系;也就是说,对于任何非null   引用值x和y,当且仅当x时,此方法返回true   和y引用相同的对象(x == y的值为true)。

Object.hashCode

  

尽可能合理实用,由hashCode方法定义   class Object确实为不同的对象返回不同的整数。

相关问题