ReentrantLock读写锁

编程

写写共享     读写互斥     写写互斥

适合读多的业务 提高效率

import java.util.concurrent.locks.ReentrantReadWriteLock;

import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;

import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

public class UseReentrantReadWriteLock {

private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

private ReadLock readLock = rwLock.readLock();

private WriteLock writeLock = rwLock.writeLock();

public void read(){

try {

readLock.lock();

System.out.println("当前线程:" + Thread.currentThread().getName() + "进入...");

Thread.sleep(3000);

System.out.println("当前线程:" + Thread.currentThread().getName() + "退出...");

} catch (Exception e) {

e.printStackTrace();

} finally {

readLock.unlock();

}

}

public void write(){

try {

writeLock.lock();

System.out.println("当前线程:" + Thread.currentThread().getName() + "进入...");

Thread.sleep(3000);

System.out.println("当前线程:" + Thread.currentThread().getName() + "退出...");

} catch (Exception e) {

e.printStackTrace();

} finally {

writeLock.unlock();

}

}

public static void main(String[] args) {

final UseReentrantReadWriteLock urrw = new UseReentrantReadWriteLock();

Thread t1 = new Thread(new Runnable() {

public void run() {

urrw.read();

}

}, "t1");

Thread t2 = new Thread(new Runnable() {

public void run() {

urrw.read();

}

}, "t2");

Thread t3 = new Thread(new Runnable() {

public void run() {

urrw.write();

}

}, "t3");

Thread t4 = new Thread(new Runnable() {

public void run() {

urrw.write();

}

}, "t4");

//读读共享

t1.start();

t2.start();

//读写互斥

// t1.start(); // R

// t3.start(); // W

//写写互斥

t3.start();

t4.start();

}

}

执行结果(读读线程同时执行,其他需要等待锁释放)

以上是 ReentrantLock读写锁 的全部内容, 来源链接: utcz.com/z/517104.html

回到顶部