JAVA JUC 读写锁

 

JAVA JUC 读写锁

 

 

应用示例

JAVA JUC 读写锁
class Demo{
    int number;
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

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

    }
    public void write(){
        lock.writeLock().lock();
        try {
            number++;
            System.out.println(Thread.currentThread().getName()+"add number");
        } finally {
            lock.writeLock().unlock();
        }
    }

}
public class writeReadLockTest {
    public static void main(String[] args) {
        Demo d = new Demo();
        for(int i =0;i<20;i++)
            new Thread(new Runnable() {
                @Override
                public void run() {
                    d.write();
                }
            },"writeThread "+i+" ").start();
        for(int i =0;i<20;i++)
            new Thread(new Runnable() {
                @Override
                public void run() {
                    d.read();
                }
            },"redaThread "+i+" ").start();

    }
}
View Code

 

上一篇:在JAVA中如何获取当前源文件名以及代码的行号


下一篇:java-JUC--异步回调