读写锁
package com.yanxizhu;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @description: 读写锁(互斥锁)
* @author: <a href="mailto:batis@foxmail.com">清风</a>
* @date: 2022/3/19 15:23
* @version: 1.0
*/
public class ReadWriteDemo {
public static void main(String[] args) {
ReadWriteTest readWriteTest = new ReadWriteTest();
new Thread(()->{
readWriteTest.write((int) (Math.random()*101));
},"写锁").start();
for(int i=1;i<50;i++){
new Thread(()->{
readWriteTest.get();
},"读锁").start();
}
}
}
class ReadWriteTest{
int num =0;
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
//读
public void get(){
readWriteLock.readLock().lock();
try{
System.out.println(num+"=="+Thread.currentThread().getName());
}finally {
readWriteLock.readLock().unlock();
}
}
//写
public void write(int i){
readWriteLock.writeLock().lock();
try{
this.num=i;
}finally {
readWriteLock.writeLock().unlock();
}
}
}
评论 (0)