public class ReadWriteLockDemo {
public static void main(String[] args) {
final Queue q = new Queue();
for (int i = 0; i < 3; i++) {
new Thread(new Runnable(){
@Override
public void run() {
while (true) {
q.set(new Random().nextInt(1000));
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
q.read();
}
}
}).start();
}
}
}
class Queue{
private int data;
private ReadWriteLock rwl = new ReentrantReadWriteLock();
public void set(int data){
rwl.readLock().lock();
this.data = data;
try {
System.out.println(Thread.currentThread().getName()
+ " ready to write data");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " "
+ data);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
rwl.readLock().unlock();
}
}
public void read() {
rwl.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName()
+ " ready to read data");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " dao "
+ data);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
rwl.writeLock().unlock();
}
}
}