標籤:
內容:讀鎖時共用的,寫鎖時互斥的(可見運行結果),都是通過AQS實現的。
public class ReentrantReadWriteLockTest {static class MyObject {private Object object;private ReadWriteLock lock = new ReentrantReadWriteLock();public void get() {lock.readLock().lock();System.out.println(Thread.currentThread().getName() + "準備讀資料!!");try {Thread.sleep(new Random().nextInt(1000));System.out.println(Thread.currentThread().getName() + "讀資料為:" + this.object);} catch (InterruptedException e) {e.printStackTrace();} finally {lock.readLock().unlock();}}public void put(Object object) {lock.writeLock().lock();System.out.println(Thread.currentThread().getName() + "準備寫資料");try {Thread.sleep(new Random().nextInt(1000));this.object = object;System.out.println(Thread.currentThread().getName() + "寫資料為" + this.object);} catch (InterruptedException e) {e.printStackTrace();} finally {lock.writeLock().unlock();}}}public static void main(String[] args) throws InterruptedException {final MyObject myObject = new MyObject();ExecutorService executor = Executors.newCachedThreadPool();for (int i = 0; i < 3; i++) {executor.execute(new Runnable() {@Overridepublic void run() {for (int j = 0; j < 5; j++)myObject.put(new Random().nextInt(1000));}});}for (int i = 0; i < 3; i++) {executor.execute(new Runnable() {@Overridepublic void run() {for (int j = 0; j < 5; j++)myObject.get();}});}executor.shutdown();}}
運行結果:
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Java-ReentrantReadWriteLock的簡單例子