码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA JUC 读写锁

时间:2020-03-13 18:37:03      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:red   i++   stat   display   rri   nal   print   hide   static   

 

技术图片

 

 

应用示例

技术图片
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 JUC 读写锁

标签:red   i++   stat   display   rri   nal   print   hide   static   

原文地址:https://www.cnblogs.com/superxuezhazha/p/12487914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!