public class ReadWriteLockTest {
public static void main(String[] args) {
final Queue q =
new
Queue();
for
(int i = 0; i < 3; i++) {
new
Thread() {
@Override
public void run() {
while
(
true
) {
q.get();
}
}
}.start();
new
Thread() {
@Override
public void run() {
while
(
true
) {
q.put(
new
Random().nextInt(10000));
}
}
}.start();
}
}
}
class Queue {
ReadWriteLock rwl =
new
ReentrantReadWriteLock();
private Object data =
null
;
public void get() {
rwl.readLock().lock();
try
{
System.out.println(Thread.currentThread().getName() +
" be ready to read data!"
);
Thread.sleep((long) (Math.random() * 1000));
System.out.println(Thread.currentThread().getName() +
" have read data :"
+ data);
}
catch
(InterruptedException e) {
e.printStackTrace();
} finally {
rwl.readLock().unlock();
}
}
public void put(Object data) {
rwl.writeLock().lock();
try
{
System.out.println(Thread.currentThread().getName() +
" be ready to write data!"
);
Thread.sleep((long) (Math.random() * 1000));
this
.data = data;
System.out.println(Thread.currentThread().getName() +
" have write data: "
+ data);
}
catch
(InterruptedException e) {
e.printStackTrace();
} finally {
rwl.writeLock().unlock();
}
}
}