并发包读写锁

/**
 * 
 * @描述: 读写锁:分为读锁和写锁,多个读锁不互斥,读锁与写锁互斥,写锁与写锁互斥,这是由JVM自己控制的,可以同时读,但不能同时写 那就上读锁;
 *               如果你的代码只读数据,可以有很多人同时读,但不能同时写那就上读锁.
 *               如果你的代码修改数据,只能有一个人在写,且不能同时写,那就上写锁
 *               
 *               总之,读的时候上读锁,写的时候上写锁,排他,我干的时候只有我能干,别人不能进来
 *               
 * @作者: Wnj .
 * @创建时间: 2017年5月16日 .
 * @版本: 1.0 .
 */

public class ReadWriteLockTest {
    
    /**
     * 产生三个线程写
     * 三个线程读
     * <功能详细描述>
     * @param args
     */
    public static void main(String[] args) {
        
        final Queue3 q3 = new Queue3();
        for (int i = 0; i < 3; i++) {
            
            //
            new Thread() {
                public void run() {
                    while (true) {
                        q3.get();
                    }
                }
                
            }.start();
            
            //
            new Thread() {
                public void run() {
                    while (true) {
                        q3.put(new Random().nextInt(10000));
                    }
                }
                
            }.start();
        }
        
    }
}

class Queue3 {
    
    private Object data = null;//共享数据,只能有一个线程能写该数据,但可以有多个线程读取它
    
    ReadWriteLock rwl = new ReentrantReadWriteLock();
    
    public void get() {
        rwl.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " ====start 准备读取data数据[可以被打乱]====");
            Thread.sleep((long)(Math.random() * 1000));
            System.out.println(Thread.currentThread().getName() + " ====end 读取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() + " ====start 准备写入data数据[不会被打乱]====");
            Thread.sleep((long)(Math.random() * 1000));
            this.data = data;
            System.out.println(Thread.currentThread().getName() + " ====end 写入data数据完毕[不会被打乱] ==== " + data);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            rwl.writeLock().unlock();
        }
        
    }
}

 

posted @ 2017-05-25 10:21  superGG  阅读(201)  评论(0编辑  收藏  举报