zoukankan      html  css  js  c++  java
  • JUC-10-ReadWriteLock读写锁

    ReadWriteLock同Lock一样也是一个接口,提供了readLock和writeLock两种锁的操作机制,一个是只读的锁,一个是写锁
     
          
     
     
    互斥原则:
    读-读能共存,
    读-写不能共存,
    写-写不能共存。
     
     
     
     
    package com.wf.zhang.juc;
    
    import java.util.concurrent.locks.ReadWriteLock;
    import java.util.concurrent.locks.ReentrantReadWriteLock;
    
    /**
     * ReadWritelock  读写锁
     *
     *
     * 写写/读写 需要"互斥"
     *
     * 读读 不需要互斥
     */
    public class TestReadWriterlock {
    
        public static void main(String[] args) {
            ReadWriterlockDemo rw = new ReadWriterlockDemo();
            //一个线程写
            new Thread(new Runnable() {
                @Override
                public void run() {
                    rw.set((int) (Math.random() * 101));
                }
            },"写锁").start();
    
    
            //100个线程读
            for (int i = 0; i <=100; i++) {
    
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        rw.get();
                    }
                }).start();
            }
    
        }
    }
    
    class ReadWriterlockDemo {
    
        private int number = 0;
    
        private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    
        //
        public void get() {
            readWriteLock.readLock().lock();
            try {
    
                System.out.println(Thread.currentThread().getName() + " 读" + number);
            } finally {
                readWriteLock.readLock().unlock();
            }
        }
    
        //
        public void set(int number) {
            this.number = number;
            readWriteLock.writeLock().lock();
            try {
    
                System.out.println(Thread.currentThread().getName() + " 写 " +number);
            } finally {
                readWriteLock.writeLock().unlock();
            }
        }
    }
    古人学问无遗力,少壮工夫老始成。 纸上得来终觉浅,绝知此事要躬行。
  • 相关阅读:
    删除commit(暂存区)中的文件(git)
    bower安装使用以及git安装
    compass模块----Utilities----Sprites精灵图合图
    compass模块----Utilities
    compass模块----Helpers
    compass模块
    compass安装
    Sass@规则
    Sass函数--颜色函数--Opacity函数
    Sass函数--颜色函数--HSL函数
  • 原文地址:https://www.cnblogs.com/wf-zhang/p/12080612.html
Copyright © 2011-2022 走看看