1
有人問我這個面試:僞碼是好的在Java中使用鎖定(面試)的最佳實踐是什麼?
//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,任何人都關心解釋和闡述?
如果他在談論['ReadWriteLock'(https://docs.oracle。 com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html),他錯了。 「只要沒有寫入器,讀取鎖就可以同時被多個讀取器線程持有,寫入鎖是排他性的。」 – EJP 2015-02-12 03:41:38
目前還不清楚'readLock.lock(16)'是什麼意思。這個問題不能一概而論。答案取決於特定類的語義是100%。你將不得不用更具體的例子編輯你的問題,否則沒有答案。 – Radiodef 2015-02-12 05:09:15
我認爲這是一個僞代碼。問題是關於概念 – 2015-02-12 05:14:42