ReentrantReadWriteLock中可以生产读锁和写锁。
读锁和读锁不互斥,写锁和任何读锁或者写锁都互斥。
demo:读锁和读锁不互斥
public static void main(String[] args) {
ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
final ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
final ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
public void run() {
try {
readLock.lock();
System.out.println(Thread.currentThread().getName() + " 开始读取数据");
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + " 读取完毕");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
readLock.unlock();
}
}
}).start();
}
}
demo读锁和写锁互斥:
public static void main(String[] args) {
ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
final ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
final ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
for (int i = 0; i < 4; i++) {
new Thread(new Runnable() {
public void run() {
try {
readLock.lock();
System.out.println(Thread.currentThread().getName() + " 开始读取数据");
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + " 读取完毕");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
readLock.unlock();
}
}
}).start();
}
new Thread(new Runnable() {
public void run() {
try {
writeLock.lock();
System.out.println(Thread.currentThread().getName() + " 开始写入数据");
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + " 读取完毕");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
writeLock.unlock();
}
}
}).start();
}
写锁和写锁互斥:
public static void main(String[] args) {
ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
final ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
final ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
for (int i = 0; i < 4; i++) {
new Thread(new Runnable() {
public void run() {
try {
writeLock.lock();
System.out.println(Thread.currentThread().getName() + " 开始写入数据");
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + " 读取完毕");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
writeLock.unlock();
}
}
}).start();
}
}
来源:oschina
链接:https://my.oschina.net/u/2250599/blog/552080