import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 读写锁 , 读写 互斥 ,写写互斥 ,对于读 比 写频繁的时候 ,优势比较明显
*/
public class ReadWriteLockTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final Queue q=new Queue();
for (int i = 0; i < 3; i++) {
new Thread(new Runnable(){
@Override
public void run() {
while(true){
q.get();
}
}
}).start();
new Thread(new Runnable(){
@Override
public void run() {
while(true){
q.put(new Random().nextInt());
}
}
}).start();
}
}
}
class Queue{
private Object data=null; //共享数据,只能有一个线程能写该数据,但是可以有多个线程同时读该数据.
ReadWriteLock rwl=new ReentrantReadWriteLock();
public void get(){
rwl.readLock().lock();
System.out.println(Thread.currentThread().getName()+" be ready to read data!");
try {
Thread.sleep((long)Math.random()*1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" have read data"+data);
rwl.readLock().unlock();
}
public void put(Object data){
rwl.writeLock().lock();
System.out.println(Thread.currentThread().getName()+" be ready to write data!");
try {
Thread.sleep((long)Math.random()*1000);
} catch (Exception e) {
e.printStackTrace();
}
this.data=data;
System.out.println(Thread.currentThread().getName()+" have write data:"+data);
rwl.writeLock().unlock();
}
}
分享到:
2016-08-03 23:46
浏览 544
评论