Java中读写锁
1.读写操作必须共用一个锁对象
读线程
public class ReadLock implements Runnable {
// 获取一个key对应的value
public void get(String key) {
ReentrantReadWriteLock.ReadLock readLock = WriteLock.rwl.readLock();
readLock.lock();
try {
//为了演示出效果,get操作再细分如下,开始—>结束视为原子步骤
System.out.println("正在做读的操作,key:" + key + " 开始");
Thread.sleep(1000);
System.out.println("正在做读的操作,key:" + key + " 结束");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
readLock.unlock();
}
}
@Override
public void run() {
for (int key = 0; key < 5; key++) {
get("" + key);
}
}
}
2.写线程
public class WriteLock implements Runnable {
public static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();//读写锁对象,两者必须共用一个锁对象
// 获取一个key对应的value
public void put(String key) {
ReentrantReadWriteLock.WriteLock writeLock =rwl.writeLock();
try {
writeLock.lock();
System.out.println("正在做写的操作,key:" + key + ",value:" + "开始.");
Thread.sleep(1000);
System.out.println("正在做写的操作,key:" + key + ",value:" + "结束.");
System.out.println();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
writeLock.unlock();
}
}
@Override
public void run() {
for (int key = 0; key < 5; key++) {
put("" + key);
}
}
}
3.测试
public class LockTest {
public static void main(String[] args) {
ReadLock readLock=new ReadLock(); //读
WriteLock writeLock=new WriteLock(); //写
Thread thread1=new Thread(readLock); //读线程
Thread thread2=new Thread(readLock); //读线程
Thread thread3=new Thread(writeLock);//写线程
thread1.start();//启动读
thread2.start();//启动读
thread3.start();//启动写
}
}
4.结果
在做写操作的时候无法进行读操作,读读操作不影响,是一并执行的,但是读操作也是必须要加读锁的,不能省略,不然也会乱
还没有评论,来说两句吧...