多線程并發(fā)之生產(chǎn)者消費(fèi)者問題與讀者寫者問題
引言
在程序界,有句流行語:我有一個(gè)問題刹孔,使用線程后,現(xiàn)在有了兩個(gè)問題髓霞。多線程并發(fā)會出現(xiàn)很多問題畦戒,其中經(jīng)典的有三個(gè)問題方库,生產(chǎn)者消費(fèi)者問題障斋、讀者寫者問題和哲學(xué)家就餐問題。
背景
并發(fā)使用多線程垃环,會得到效率的提升。由于這些線程的執(zhí)行順序未知遂庄,這會由于線程間的執(zhí)行順序?qū)е潞芏鄦栴}。這些問題最后都可以歸納為兩類問題——生產(chǎn)者消費(fèi)者問題與讀者寫者問題秸谢。
在這里,將嘗試解決這類問題钮追。
解決方案
不論生產(chǎn)者消費(fèi)者問題阿迈,還是讀者寫者問題元媚,最終都可以簡單的歸納為一下模型苗沧。
獲取權(quán)限
執(zhí)行
釋放權(quán)限
下面將給出獲取權(quán)限和釋放權(quán)限的代碼
生產(chǎn)者消費(fèi)者問題代碼
public class ProducerConsumerLockUtils {
public static int num = 0;
private static int MAX = 6;
private static Lock producerConsumerLock = new ReentrantLock();
public synchronized void acquireProducerLock(){
while (num >= MAX) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
producerConsumerLock.lock();
}
public synchronized void releaseProducerLock(){
num++;
this.notify();
producerConsumerLock.unlock();
}
public synchronized void acquireConsumerLock(){
while (num < 1) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
producerConsumerLock.lock();
}
public synchronized void releaseConsumerLock(){
num--;
this.notify();
producerConsumerLock.unlock();
}
}
讀者寫者問題代碼
public class ReaderWriterLockUtils {
private int readerNum = 0;
private static Lock readerWriterLock = new ReentrantLock();
public synchronized void acquireReaderLock() {
while (readerNum == 0) {
readerWriterLock.lock();
}
readerNum++;
}
public synchronized void releaseReaderLock() {
readerNum--;
while (readerNum == 0) {
readerWriterLock.unlock();
}
this.notify();
}
public synchronized void acquireWriterLock() {
while (readerNum > 0) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
readerWriterLock.lock();
}
public synchronized void releaseWriterLock() {
this.notifyAll();
readerWriterLock.unlock();
}
}