9 Java并发ReadWriteLock接口
程序员文章站
2022-07-12 11:31:05
...
java.util.concurrent.locks.ReadWriteLock接口允许一次读取多个线程,但一次只能写入一个线程。
- 读锁 - 如果没有线程锁定ReadWriteLock进行写入,则多线程可以访问读锁。
- 写锁 - 如果没有线程正在读或写,那么一个线程可以访问写锁。
锁方法
以下是Lock类中可用的重要方法的列表。
编号 | 方法 | 描述 |
---|---|---|
1 | public Lock readLock() | 返回用于读的锁。 |
2 | public Lock writeLock() | 返回用于写的锁。 |
示例
以下ReadWriteLockTest程序演示了ReadWriteLock接口的这些方法。这里我们使用readlock()获取读锁定和writeLock()来获取写锁定。
package ThreadMethod;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockTest {
private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
private static String message = "a";
public static void main(String[] args) throws InterruptedException{
Thread t1 = new Thread(new WriterA());
t1.setName("Writer A");
Thread t2 = new Thread(new WriterB());
t2.setName("Writer B");
Thread t3 = new Thread(new Reader());
t3.setName("Reader");
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
}
static class Reader implements Runnable {
public void run() {
if(lock.isWriteLocked()) {
System.out.println("Write Lock Present.");
}
lock.readLock().lock();
try {
Long duration = (long) (Math.random() * 10000);
System.out.println(Thread.currentThread().getName()
+ " Time Taken " + (duration / 1000) + " seconds.");
Thread.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() +": "+ message );
lock.readLock().unlock();
}
}
}
static class WriterA implements Runnable {
public void run() {
lock.writeLock().lock();
try {
Long duration = (long) (Math.random() * 10000);
System.out.println(Thread.currentThread().getName()
+ " Time Taken " + (duration / 1000) + " seconds.");
Thread.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
message = message.concat("a");
lock.writeLock().unlock();
}
}
}
static class WriterB implements Runnable {
public void run() {
lock.writeLock().lock();
try {
Long duration = (long) (Math.random() * 10000);
System.out.println(Thread.currentThread().getName()
+ " Time Taken " + (duration / 1000) + " seconds.");
Thread.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
message = message.concat("b");
lock.writeLock().unlock();
}
}
}
}
运行
Write Lock Present.
Writer A Time Taken 4 seconds.
Writer B Time Taken 2 seconds.
Reader Time Taken 6 seconds.
Reader: aab
上一篇: Java注解应用场景
推荐阅读
-
Java并发系列[9]----ConcurrentHashMap源码分析
-
Java并发编程之Executor接口的使用
-
JAVA并发编程(五):创建线程的第三种方式:实现Callable接口
-
Java多线程/并发06、线程锁Lock与ReadWriteLock
-
9 Java并发ReadWriteLock接口
-
Java-并发-锁-ReadWriteLock
-
Java 多线程高并发 3.5 — ReadWriteLock 读写锁使用
-
Java并发线程编程基础(3)-ReadWriteLock读写锁
-
Java 并发 —— 读写锁(ReadWriteLock)
-
Java并发--读写锁(ReadWriteLock)