這篇文章主要介紹了Java多執行緒之readwritelock讀寫分離的相關內容,文中涉及具體實例程式碼,具有一定參考價值,需要的朋友可以了解下。
在多執行緒開發中,經常會出現一種情況,我們希望讀寫分離。就是對於讀取這個動作來說,可以同時有多個線程同時去讀取這個資源,但是對於寫這個動作來說,只能同時有一個線程來操作,而且同時,當有一個寫線程在操作這個資源的時候,其他的讀線程是不能來操作這個資源的,這樣就極大的發揮了多線程的特點,能很好的將多線程的能力發揮出來。
在Java中,ReadWriteLock這個介面就為我們實現了這個需求,透過他的實作類ReentrantReadWriteLock我們可以很簡單的實現剛才的效果,下面我們使用一個例子來說明這個類的用法。
package com.bird.concursey.charpet3; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class PricesInfo { private double price1; private double price2; private ReadWriteLock lock; public PricesInfo() { price1 = 1.0; price2 = 2.0; lock = new ReentrantReadWriteLock(); } public double getPrice1() { //读取资源锁定 lock.readLock().lock(); double value = price1; lock.readLock().unlock(); return value; } public double getPrice2() { lock.readLock().lock(); double value = price2; lock.readLock().unlock(); return value; } public void setPrices(double price1, double price2) { lock.writeLock().lock(); this.price1 = price1; this.price2 = price2; lock.writeLock().unlock(); } }
下面是讀取和寫入兩個不同的類別
package com.bird.concursey.charpet3; public class Reader implements Runnable { private PricesInfo pricesInfo; public Reader(PricesInfo pricesInfo) { this.pricesInfo = pricesInfo; } @Override public void run() { for (int i = 0; i < 10; i++) { System.out.printf("%s: Price 1: %f\n", Thread.currentThread() .getName(), pricesInfo.getPrice1()); System.out.printf("%s: Price 2: %f\n", Thread.currentThread() .getName(), pricesInfo.getPrice2()); } } }
package com.bird.concursey.charpet3; public class Writer implements Runnable { private PricesInfo pricesInfo; public Writer(PricesInfo pricesInfo) { this.pricesInfo = pricesInfo; } @Override public void run() { for (int i = 0; i < 3; i++) { System.out.printf("Writer: Attempt to modify the prices.\n"); pricesInfo.setPrices(Math.random() * 10, Math.random( ) * 8); System.out.printf("Writer: Prices have been modified.\n"); try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { PricesInfo pricesInfo = new PricesInfo(); Reader readers[] = new Reader[5]; Thread threadsReader[] = new Thread[5]; for (int i = 0; i < 5; i++){ readers[i] = new Reader(pricesInfo); threadsReader[i] = new Thread(readers[i]); } Writer writer = new Writer(pricesInfo); Thread threadWriter = new Thread(writer); for (int i = 0; i < 5; i++){ threadsReader[i].start(); } threadWriter.start(); } }
總結
以上是Java多執行緒之readwritelock讀寫分離的實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!