线程之ReadWriteLock

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ThreadReadWriteLock {

    /**
     * 读写锁
     * 读得时候还能读
     * 读的时候不能写
     * 写的时候不能读
     * 写的时候不能写
     */
    public static void main(String[] args) {
        final ReadWrite readWrite = new ReadWrite();
        for(int i=0;i<3;i++){
            new Thread(){
                public void run() {
                    while(true){
                        readWrite.read();
                    }
                }}.start();
            new Thread(){
                public void run() {
                    while(true){
                        readWrite.write(new Random().nextInt(1000));
                    }
                }}.start();
        }
    }
}
class ReadWrite{
    Object data = null;
    ReadWriteLock rwl = new ReentrantReadWriteLock();
    public void read(){
        rwl.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+" ready to read data");
            Thread.sleep((long)(Math.random()*1000));
            System.out.println(Thread.currentThread().getName()+" has read " + data);
        }catch(InterruptedException e){
            e.printStackTrace();
        }finally{
            rwl.readLock().unlock();
        }
    }
    public void write(Object data){
        rwl.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+" ready to write data");
            this.data = data;
            Thread.sleep((long)(Math.random()*1000));
            System.out.println(Thread.currentThread().getName()+" has written " + data);
        }catch(InterruptedException e){
            e.printStackTrace();
        }finally{
            rwl.writeLock().unlock();
        }
        
    }
}

 

posted @ 2014-03-15 23:58  huidaoli  阅读(140)  评论(0编辑  收藏  举报