我在采访中被问到这个问题:伪代码是好的
//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的解决方案,任何人都需要解释和阐述?
答案 0 :(得分:2)
理念是读者只有在没有写入的情况下才能阅读。换句话说,读取是无同步的。所以16个线程可以同时读取。 但是,当您想要写入时,锁定所有内容(读取和写入过程)并仅执行写入操作。 Interviewer可能已经从ConcurrentHashMap中获取了这个想法,因为concurrencyLevel的默认值是16。
我建议您查看http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html