抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

使用juc库中的Semaphore实现ReadwriteLock

使用读锁和写锁实现读共享和写独占特性,内部维护readCount表示读线程的个数。

实现代码如下:

import java.util.concurrent.Semaphore;  
  
public class TestLock {  
  
  
private volatile int readCount = 0;  
private Semaphore countLock = new Semaphore(1);  
private Semaphore writeLock = new Semaphore(1);  
  
  
public void readlock() throws InterruptedException {  
countLock.acquire();  
if (readCount == 0) writelock();  
readCount += 1;  
countLock.release();  
}  
  
public void readunlock() throws InterruptedException {  
countLock.acquire();  
readCount--;  
if (readCount == 0) writeunlock();  
countLock.release();  
}  
  
  
public void writelock() throws InterruptedException {  
writeLock.acquire();  
}  
  
public void writeunlock() {  
writeLock.release();  
}  
  
}

测试代码如下:

import java.util.concurrent.TimeUnit;  
import java.util.concurrent.locks.ReadWriteLock;  
import java.util.concurrent.locks.ReentrantReadWriteLock;  
  
public class Test {  
private static TestLock testLock = new TestLock();  
private static ReadWriteLock lock = new ReentrantReadWriteLock();  
private static int num = 0;  
public static void main(String[] args) throws InterruptedException {  
lock.readLock().lock();  
for (int i = 0; i < 20; i++) {  
add();  
}  
for (int i = 0; i < 5; i++) {  
read();  
}  
}  
  
private static void read() {  
new Thread(()-> {  
try {  
testLock.readlock();  
} catch (InterruptedException e) {  
throw new RuntimeException(e);  
}  
System.out.println(Thread.currentThread().getName() + "start!");  
System.out.println(num);  
System.out.println(Thread.currentThread().getName() + "over!");  
try {  
testLock.readunlock();  
} catch (InterruptedException e) {  
throw new RuntimeException(e);  
}  
}).start();  
}  
  
private static void add() {  
new Thread(()-> {  
try {  
testLock.writelock();  
} catch (InterruptedException e) {  
throw new RuntimeException(e);  
}  
System.out.println(Thread.currentThread().getName() + "start!");  
System.out.println(num + "->" + ++num);  
System.out.println(Thread.currentThread().getName() + "over!");  
testLock.writeunlock();  
}).start();  
}  
}

评论