在读写/写写的情况下需要用读写锁来保证线程安全
ReentrantReadWriteLock
Lock接口的实现类之一
普通锁:需要实现类ReentrantLock;
- Lock lock=new ReentrantLock();
读写锁: 需要实现类ReentrantReadWriteLock - ReentrantReadWriteLock lock=new ReentrantReadWriteLock();
锁的是访问器的设置值于得到值;相当于读和写
package ReentrantReadWriteLock读写锁;
//并发包下的luck接口下的 ReetrantReadWriteLock实现类 是lock的一个实现类
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Number {
private int number;
ReentrantReadWriteLock lock=new ReentrantReadWriteLock();
public int getNumber() {
try {
lock.readLock().lock();
System.out.println("number变量的值为:"+number);
return number;
}finally {lock.readLock().unlock();}
}
public void setNumber(int number) {
try {
lock.writeLock().lock();
this.number = number;
System.out.println(Thread.currentThread().getName()+" "+number);
}finally {
lock.writeLock().unlock();
}
}
}
测试
package ReentrantReadWriteLock读写锁;
public class NumberTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Number number =new Number();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
number.setNumber((int)(Math.random()*10));
}
},"Write:").start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
number.getNumber();
}
},"Reader:"+i).start();
}
}