在Java中使用锁的最佳实践是什么(访谈)?

在Java中使用锁的最佳实践是什么(访谈)?,java,multithreading,locking,java.util.concurrent,Java,Multithreading,Locking,Java.util.concurrent,我在采访中被问到:伪代码可以吗 //Assume you have a list or A Queue //1 - How do you make Sure pushing to list is safe? //1 - My Ans: void push(Element e){ Synchronized(this){ list.push(e); } } //2- Inte

我在采访中被问到:伪代码可以吗

//Assume you have a list or A Queue
//1 - How do you make Sure pushing to list is safe?
//1 - My Ans: 
        void push(Element e){
            Synchronized(this){
               list.push(e);
              }
             }
//2- Interviewer said Ok, there is better way to do this without Synchronized word
          void push(Element e){
              writeLock.Lock();
              list.push(e);
              writeLock.UnLock();
             }
//3- He said Ok, but wouldn't work if there are 16 threads, How can I make sure only one thread can write?  His answer was more like a "Semaphore"
       void push(Element e){
             readLock.lock(16), //meaning get read lock on all 16 thrds
              writeLock.Lock(); //then allow to write
              list.push(e);
              writeLock.UnLock();
              readLock.Unlock()
             }

我不确定我是否理解他在#3的解决方案,有人愿意解释和详细说明吗?

想法是读者只能在没有写作的情况下阅读。换句话说,阅读是无同步的。所以16个线程可以并发读取。 但是,当您想要写入时,您会锁定所有内容(读和写过程),并且只执行写入操作。采访者可能从ConcurrentHashMap中得到了这个想法,因为ConcurrentyLevel的默认值是16


我建议你看看

如果他在说,他错了。“只要没有写入程序,读锁可以由多个读线程同时持有。写锁是独占的。”不清楚
readLock.lock(16)
的含义是什么。这个问题不能一概而论。答案100%取决于特定类的语义是什么。你必须用一个更具体的例子来编辑你的问题,否则没有答案。我认为这是一个伪代码。问题是关于concept@HamedMoghaddam问题不可能是关于这个概念。正确答案完全取决于API的语义。Java中存在一个具有不同语义的API的事实证明了这一点。@EJP在问题的第一行我看到“伪代码没问题”。这在上下文中并不清楚,但在我看来user1529412意味着它不是确切的代码。这就是为什么我认为这个代码不一定是采访中所问的确切代码,它可能是一个概念性的问题