package cn.hctech2006.concurrent.thread41;
import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 用读写锁实现读者写者问题
*/
public class ReadWriteLockTest {
public static void main(String[] args) {
Queue3 queue3 = new Queue3();
for(int i = 0; i < 3; i ++){
new Thread("read-"+i){
public void run(){
while (true){
queue3.get();
}
}
}.start();
}
for(int i = 0; i < 3; i ++){
new Thread("write-"+i){
public void run(){
while (true){
try {
Thread.sleep(1000);
queue3.put(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
}
class Queue3{
private Object data = null;
private ReentrantReadWriteLock 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()*100);
System.out.println(Thread.currentThread().getName()+
"have read data");
}catch (InterruptedException e){
e.printStackTrace();
}finally {
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(1000);
this.data=data;
System.out.println(Thread.currentThread().getName()
+"have write data:"+data);
}catch (InterruptedException e){
e.printStackTrace();
}finally {
rwl.writeLock().unlock();
}
}
}
Java实现读者写者问题
最新推荐文章于 2022-03-01 23:53:35 发布