ReentranReadWriteLock使用案例
/**
* ReentranReadWriteLock 使用案例
* 读线程共享
* 写线程互斥
*/
public class ReentrantReadWriteLockExample {
private String news;
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public String readNews() {
lock.readLock().lock();
try {
// 读线程睡眠1秒, 观察打印时间
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")) + " is reading the news: " + news);
return news;
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.readLock().unlock();
}
}
public void writeNews(String updatedNews) {
lock.writeLock().lock();
try {
// 让写线程睡眠两秒,这样可以观察到写线程阻塞
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh:mm:ss")) + " is updating the news to: " + updatedNews);
news = updatedNews;
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.writeLock().unlock();
}
}
public static void main(String[] args) {
ReentrantReadWriteLockExample newsData = new ReentrantReadWriteLockExample();
// 创建多个读线程
for (int i = 0; i < 10; i++) {
new Thread(() -> {
newsData.readNews();
}).start();
}
// 创建多个写线程
for (int i = 0; i < 5; i++) {
new Thread(()->{
newsData.writeNews("Breaking news: JavaAssistant is awesome!");
}).start();
}
}
}
输出结果
从结果可以看出,读线程是同时读取了news,而写线程则是一个个的读。
Thread-0 10:11:45 is reading the news: null
Thread-7 10:11:45 is reading the news: null
Thread-6 10:11:45 is reading the news: null
Thread-1 10:11:45 is reading the news: null
Thread-5 10:11:45 is reading the news: null
Thread-3 10:11:45 is reading the news: null
Thread-2 10:11:45 is reading the news: null
Thread-9 10:11:45 is reading the news: null
Thread-4 10:11:45 is reading the news: null
Thread-8 10:11:45 is reading the news: null
Thread-10 10:11:47 is updating the news to: Breaking news: JavaAssistant is awesome!
Thread-11 10:11:49 is updating the news to: Breaking news: JavaAssistant is awesome!
Thread-12 10:11:51 is updating the news to: Breaking news: JavaAssistant is awesome!
Thread-13 10:11:53 is updating the news to: Breaking news: JavaAssistant is awesome!
Thread-14 10:11:55 is updating the news to: Breaking news: JavaAssistant is awesome!