JUC编程(五)-ReadWriteLock
作者:互联网
七.ReadWriteLock
ReadWriteLock读写锁实现类为ReentrantReadWriteLock。用于控制读写数据,一次只有一个线程( 写入线程)可以修改共享数据,任何数量的线程都可以同时读取数据。
通过readLock()控制读数据,writeLock()控制写数据。
public class ReadWrite {
public static void main(String[] args) {
Cache cache = new Cache();
for (int i = 0; i < 3; i++) {
final String t = String.valueOf(i);
new Thread(()->{
try {
cache.write(t,t);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
for (int i = 0; i < 3; i++) {
final String t = String.valueOf(i);
new Thread(()->{
cache.read(t);
}).start();
}
}
}
class Cache{
private volatile Map<String,Object> map = new HashMap<>();
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void write(String key,Object value) throws InterruptedException {
// 写,同一时刻只有一个线程写
readWriteLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName()+" writing...");
map.put(key,value);
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread().getName()+" write over");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}
public void read(String key){
// 读,多个线程可以同时读
readWriteLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()+" reading...");
System.out.println(Thread.currentThread().getName()+" value:"+map.get(key));
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
}
}
Thread-1 writing...
Thread-1 write over
Thread-0 writing...
Thread-0 write over
Thread-2 writing...
Thread-2 write over
Thread-4 reading...
Thread-4 value:1
Thread-5 reading...
Thread-3 reading...
Thread-5 value:2
Thread-3 value:0
标签:JUC,String,Thread,...,ReadWriteLock,编程,value,write,线程 来源: https://www.cnblogs.com/tao-gak567/p/15389785.html