下面的读写锁代码出现了IllegalMonitorStateException异常,查了好久没找出原因
public static void main(String[] args) {
final ReadWrite readWrite = new ReadWrite();
for(int i=0;i<3;i++){
new Thread(){
public void run() {
while(true){
readWrite.read();
}
}}.start();
new Thread(){
public void run() {
while(true){
readWrite.write(new Random().nextInt(1000));
}
}}.start();
}
}
}
class ReadWrite{
Object data = null;
ReadWriteLock rwl = new ReentrantReadWriteLock();
public void read(){
rwl.readLock().lock();
try{
System.out.println(Thread.currentThread().getName()+" ready to read data");
Thread.sleep((long)(Math.random()*1000));
System.out.println(Thread.currentThread().getName()+" has read " + data);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
rwl.readLock().unlock();
}
}
public void write(Object data){
rwl.writeLock().unlock();
try{
System.out.println(Thread.currentThread().getName()+" ready to write data");
this.data = data;
Thread.sleep((long)(Math.random()*1000));
System.out.println(Thread.currentThread().getName()+" has written " + data);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
rwl.writeLock().unlock();
}
} |