此实例是关于读写同步锁的问题。
import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockTest {
public static void main(String[] args) {
final Queue queue = new Queue();
for(int i =1;i<=3;i++){
new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep((long)Math.random()*100000);
queue.put(new Random().nextInt(100000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep((long)Math.random()*100000);
queue.get();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
}
class Queue{
//共享数据,只能有一个线程对其能更改
private Object data = 85;
ReadWriteLock rwl = new ReentrantReadWriteLock();
public void get(){
rwl.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " be ready to read data !");
System.out.println(Thread.currentThread().getName() + " have read data :" + data);
}finally{
rwl.readLock().unlock();
}
}
public void put(Object data){
rwl.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " be ready to write data !");
this.data = data ;
System.out.println(Thread.currentThread().getName() + " have write data :" + data);
}finally{
rwl.writeLock().unlock();
}
}
}