java读写锁ReadWriteLock

package com.java.concurrent;

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

public class TestReadWriteLock {

    public static void main(String[] args) {
        final ReadWriteLockDemo rw2 = new ReadWriteLockDemo();
        new Thread(new Runnable() {
            
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                rw2.set(20);
                
            }
        },"Write:").start();

        
        new Thread(new Runnable() {
            
            public void run() {
                while(true)
                rw2.get();
            }
        },"Read").start();
        
    }


}

class ReadWriteLockDemo {
    private int number = 0;
    // 定义一个读写锁
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    //
    public void get() {
        //添加读锁
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + ":" + number);
        } finally {
            lock.readLock().unlock();
        }
    }

    // 写数据
    public void set(int number) {
        //创建写锁
        lock.writeLock().lock();
        try{
        System.out.println(Thread.currentThread().getName()+":"+number);

        this.number = number;
        }finally{
            lock.writeLock().unlock();
        }
    }

}

 

    原文作者:fliay
    原文地址: http://www.cnblogs.com/fliay/p/7681038.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞