Java ReentrantreadWritelock示例
时间:2020-02-23 14:35:09 来源:igfitidea点击:
在本教程中,我们将看到ReentrantReadWritelock示例。
ReentrantReadWriteLock支持Reentrantlock的语义,也支持ReadWriteLock。
ReadWriteLock有两个锁,一个用于读取,一个用于写入。
如果没有写入请求,可以获得来自多个线程的读锁的请求。
如果有写请求,则无法在该资源上获取读取或者写入锁定的其他线程。
ReentrantReadWriteLock示例:
它是ReadWridelock接口的实现。
它有两种锁定: ReaderLock
和 WriterLock
。
让我们在一个例子的帮助下了解它:
我们将有三个可运行的接口。
读者,WriteReven和Writerodd。
读者:它将读取数字变量。
WriteReven:它将写入数字。
Writerodd:它会将奇数数字写入数字。
我们将使用reentrantreadWriteLock公平为真实。
package org.igi.theitroad; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReentrantReadWriteLockExampleMain { private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true); private static String number = "0"; public static void main(String[] args) throws InterruptedException{ Thread t1 = new Thread(new Reader(),"Read 1"); Thread t2 = new Thread(new Reader(),"Read 2"); Thread t3 = new Thread(new WriterOdd(),"Write odd"); Thread t4 = new Thread(new WriterEven(),"Write even"); t1.start(); t2.start(); t3.start(); t4.start(); t1.join(); t2.join(); t3.join(); t4.join(); } static class Reader implements Runnable { public void run() { for(int i = 0; i<= 10; i ++) { lock.readLock().lock(); System.out.println(Thread.currentThread().getName() + " ---> Number is " + number ); lock.readLock().unlock(); } } } static class WriterOdd implements Runnable { public void run() { for(int i = 1; i<= 7; i+=2) { try { lock.writeLock().lock(); System.out.println("Writer odd is writing"); number = number.concat(" "+i); } finally { lock.writeLock().unlock(); } } } } static class WriterEven implements Runnable { public void run() { for(int i = 2; i<= 8; i +=2) { try { lock.writeLock().lock(); System.out.println("Writer Even is writing"); number = number.concat(" "+i); } finally { lock.writeLock().unlock(); } } } } }