• ReentreantLock:重入锁


    ReentreantLock:重入锁

    参考:https://www.cnblogs.com/nullzx/p/4968674.html

    一)、 ReentrantLock与synchronized的区别:

    1).JDK1.5,在高并发的情况下,ReentrantLock的性能比Synchronized的性能好

    2).JDK1.6,中Jvm对其进行了优化,两者差别不大。

    3).使用ReentrantLock需要在finally中显示的释放锁,否则,程序出现异常就无法

    ​ 释放锁。

    4).使用Synchronized,JVM虚拟机总会在最后自动的释放synchronized锁。

    二)、ReentrantLock的特点

    分类: 公平锁/非公平锁

    1).公平锁:

    ​ 特点:保证锁等待队列中各线程是公平的,对锁的获取先进先出

    2).非公平锁:

    ​ 特点:申请锁的线程可能插队,后申请锁的线程可能后进先出

    性能比较: 非公平锁的性能优于公平锁,优先选择非公平锁。

    构造函数:指定锁的类型

    public ReentrantLock(boolean fair)
    

    3). 主要方法:

    lock(): 获取锁,若锁已占用,则等待

    tryLock(): 尝试获取锁,不等待立即返回,没有获得锁返回false,获得锁返回true

    tryLock(long Time, TimeUnit unit): 在指定时间里尝试获取锁

    lockInterruptibly(): 获得锁,但优先响应中断

    unlock(): 释放锁

    三)、Lock()的使用

    lock():

    特点:

    1).返回值为void,没有锁则一直等待,直到获取锁。

    2).等待期间,线程不响应中断

    public void lock() {
            sync.lock();
        }
    

    lock()的使用:

    import java.util.concurrent.locks.ReentrantLock;
    
    /**
     * 测试ReentrantLock获取锁的方法有什么不同
     *    使用lock()来获取锁
     */
    public class Lock implements Runnable{
        //保证每一个线程都使用同一把锁
        private static ReentrantLock lock = new ReentrantLock();
    
    
        @Override
        public void run() {
            while (true) {
                //获得锁后,模拟线程进行业务操作
                try {
                    //使用lock()获取锁
                    lock.lock();
                    //输出当前获得锁的线程对象
                    System.out.println("lock " + Thread.currentThread().getName());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName()+ " is Interrupted");
                } finally {
                    //需要在finally中显示的释放锁,否则,程序发生异常,无法释放锁。
                    lock.unlock();
                    System.out.println("unlock " + Thread.currentThread().getName());
                }
                break;
            }
        }
    
    }
    

    测试类:

    public class LockTest {
        public static void main(String[] args) {
            Lock reentrantLock = new Lock();
            Thread first = new Thread(reentrantLock,"FirstThread");
            Thread second = new Thread(reentrantLock,"SecondThread");
            first.start();
            second.start();
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //中断线程
            
            /**
             * 设置线程的中断位,调用second.interrupt(),线程的中断位置为true,
             * 线程的wait()、sleep()、jion()等方法会监控中断位的状态,若状态为true则抛出InterruptedExecption
             * 此时,线程不是停止状态,可以执行catch中的业务逻辑。
             */
    
            second.interrupt();
    
        }
        //结论:使用lock()操作,如果线程未得到锁将会一直等待,直到有其他的线程释放锁,线程在等待期间,不会响应中断
    }
    
    

    结果:

    lock FirstThread
    unlock FirstThread
    lock SecondThread
    SecondThread is Interrupted
    unlock SecondThread
    

    结果分析:

    1).调用lock.lock()获取锁失败,线程则一直在等待。

    2).线程等待锁期间,不响应中断。

    3).线程调用interrupt()方法,方法本身不会抛出InterruptedExecption,只是改变

    ​ 了线程的状态位为true, 当前线程的sleep()、wait()、jion()方法识别到了状态位

    ​ 改变,当状态位为true时抛出InterruptExecption,此时,处于sleep()、wait()

    ​ jion()状态的线程苏醒,执行catch(){}中的语句,线程抛出InterruptedExecption

    后,状态位重新置为false。

    四)、lockInterruptibly()的使用:

    特点:

    1).返回值为void,获取锁,如果获取失败,则一直等待,且优先处理中断

    2).获取锁时会先使用Interrupt()判断中断状态并重置中断状态,当中断状态位

    ​ true时,抛出InterruptedExecption,否则执行获取锁操作

      public void lockInterruptibly() throws InterruptedException {
            sync.acquireInterruptibly(1);
        }
    
    //优先响应中断
     public final void acquireInterruptibly(int arg)
                throws InterruptedException {
            //判断中断状态,Thread.interrupted(),获取当前线程的中断状态,并重置
            if (Thread.interrupted())
                throw new InterruptedException();
            if (!tryAcquire(arg))
                doAcquireInterruptibly(arg);
        }
    

    lockInterruptibly()的使用:

    /**
     * 测试使用lockInterruptibly()来获取锁
     *    lockInterruptibly(): 获取锁,当优先响应中断
     */
    public class InterruptedLock implements Runnable{
        /**
         *   创建共有的锁对象
         */
        private static ReentrantLock lock = new ReentrantLock();
        @Override
        public void run() {
            while (true) {
                //获取锁
                try {
                    //lock.lockInterruptibly()方法调用放在try的外部,否则,若线程发生中断,finally调用lock.unlock()会抛出IllegalMonitorStateExecption
                    lock.lockInterruptibly();
                    //业务逻辑要放在另一个try里边,因为当线程调用interrupt()会抛出InterruptedException,再finally调用unlock()会抛IllegalMonitorStateExecption
                    try {
                        //输出当前获得锁的线程对象
                        System.out.println("lock " + Thread.currentThread().getName());
                        //模拟获得锁后的业务逻辑
                        Thread.sleep(1000);
                    } finally {
                        lock.unlock();
                        //释放锁
                        System.out.println("unlock "+Thread.currentThread().getName());
                        break;
                    }
                }catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + " is interrupted");
                }
             }
        }
    }
    
    

    测试:

    /**
     * 测试优选处理中断的锁,在等待期间,可以优先的处理中断
     *
     */
    public class InterruptedLockTest {
        public static void main(String[] args){
            InterruptedLock interruptedLock =  new InterruptedLock();
            Thread first = new Thread(interruptedLock, "FirstThread");
            Thread second = new Thread(interruptedLock, "SecondThread");
            first.start();
            second.start();
            //线程中断
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            second.interrupt();
        }
    }
    

    结果:

    lock FirstThread
    SecondThread is interrupted
    unlock FirstThread
    lock SecondThread
    unlock SecondThread
    

    结果分析:

    1).线程获取锁失败,进入等待状态

    2).在线程等待期间,响应中断

    注意事项:

    lockInterruptibly()在使用时,需要两个try语句,lockInterruptibly()声明在第一个try中,并对应catch处理,业务逻辑在第二个try中,关闭锁也在第二个try的finally中。

    while(true){
        ...
            try{
                lock.lockInterruptibly();
                try{
                    ...
                        
                }finally{
                    lock.unlock();
                }
            }catch(InterruptedExecption e){
                
            }
        
    }
    

    原因:如果使用一层的try,当线程的中断状态为true时,会抛出异常,进行catch处

    ​ 理,之后在finally释放锁,由于线程未获得锁,调用lock.unlock()会抛出

    ​ IllegalMonitorStateExecption。

    五)、tryLock()的使用:

    特点:

    1).返回值为void,立即返回获取锁的结果,获取成功返回true,失败返回false

    2).尝试获取锁期间,不响应中断。

     public boolean tryLock() {
            return sync.nonfairTryAcquire(1);
        }
    

    tryLock()的使用:

    import java.util.concurrent.locks.ReentrantLock;
    
    /**
     * tryLock():尝试获取锁
     */
    public class TryLock implements Runnable{
        /**
         * 锁对象
        */
        private static ReentrantLock lock = new ReentrantLock();
        @Override
        public void run() {
            while(true){
                //尝试获取锁,立即返回获取结果,成功则返回true,失败返回false
               if( lock.tryLock()){
                   try {
                       System.out.println("lock "+Thread.currentThread().getName());
                       Thread.sleep(1000);
                   } catch (InterruptedException e) {
                       System.out.println(Thread.currentThread().getName()+" is Interrupted");
                   }finally{
                       //释放锁
                      lock.unlock();
                       System.out.println("unlock "+ Thread.currentThread().getName());
                       break;
                   }
               }else{
                   //获取锁失败
                   System.out.println("unable lock "+Thread.currentThread().getName());
               }
            }
        }
    }
    
    

    测试类:

    public class TryLockTest {
        public static void main(String[] args) throws InterruptedException {
            TryLock tryLock = new TryLock();
            Thread first = new Thread(tryLock,"FirstThread");
            Thread second = new Thread(tryLock, "SecondThread");
            first.start();
            second.start();
            Thread.sleep(600);
            //中断second线程
            second.interrupt();
    
        }
    }
    

    结果:

    lock FirstThread
    unable lock SecondThread
    unable lock SecondThread
    unable lock SecondThread
    unable lock SecondThread
    unable lock SecondThread
    unable lock SecondThread
    unable lock SecondThread
    unable lock SecondThread
    unable lock SecondThread
    unable lock SecondThread
    .................... //一大堆获取锁的输出
    unlock FirstThread
    lock SecondThread
    SecondThread is Interrupted
    unlock SecondThread
    

    结果分析:

    1).使用tryLock(),线程一直判断获取锁

    2).线程在尝试获取锁期间,不响应中断

    六)、tryLock(long time, TimeUnit unit)的使用

    特点:

    1).在指定的时间内等待锁,若在指定的时间内获取到锁返回true,未获取到锁,返

    ​ 会false。

    2).在等待锁时优先处理中断,当线程的中断状态为true时,tryLock(long time,

    ​ TimeUnit unit)抛出InterruptExecption

     public boolean tryLock(long timeout, TimeUnit unit)
                throws InterruptedException {
            return sync.tryAcquireNanos(1, unit.toNanos(timeout));
        }
    
        public final boolean tryAcquireNanos(int arg, long nanosTimeout)
                throws InterruptedException {
            //判断线程的中断状态
            if (Thread.interrupted())
                throw new InterruptedException();
            return tryAcquire(arg) ||
                doAcquireNanos(arg, nanosTimeout);
        }
    

    tryLock(long time, TimeUnit unit)的使用:

    /**
     * 在指定时间里等待锁
     */
    public class TryLockOnTime implements Runnable{
        private static ReentrantLock lock = new ReentrantLock();
        @Override
        public void run() {
            while(true) {
                //获取锁
                try {
                    //获取锁之前,先判断线程的中断状态,若中断状态为true,抛出InterruptedExecption
                    if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
                        try {
                            System.out.println("lock " + Thread.currentThread().getName());
                            Thread.sleep(1000);
    
                        } finally {
                            System.out.println("unlock " + Thread.currentThread().getName());
                            //释放锁
                            lock.unlock();
                        }
                        break;
                    } else {
                        System.out.println("unable lock " + Thread.currentThread().getName());
                    }
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + " is Interrupted");
                }
            }
        }
    }
    
    

    测试:

    public class TryLockOnTimeTest {
        public static void main(String[] args) throws InterruptedException {
            TryLockOnTime tryLockOnTime = new TryLockOnTime();
            Thread first = new Thread(tryLockOnTime, "FirstThread");
            Thread second = new Thread(tryLockOnTime, "SecondThread");
            first.start();
            second.start();
            Thread.sleep(1000);
            second.interrupt();
        }
    }
    
    

    结果:

    lock FirstThread
    unable lock SecondThread
    SecondThread is Interrupted
    unlock FirstThread
    lock SecondThread
    unlock SecondThread
    

    结果分析:

    1).使用tryLock(long time, TimeUnit unit)会在指定时间内等待锁,若没有获得锁

    ​ 返回false,获得锁返回true.

    2).等待锁,获取锁时,优先响应中断。

    七)、总结

    lock(): 获取锁,返回值为void,未获取到锁,线程一直处于等待锁状态,在等待期

    ​ 不会响应中断。

    lockInterruptibly(): 获取锁,返回值为void,未获取到锁,线程一直处于等待锁

    ​ 状态,在等待锁期间,优先响应中断。

    tryLock(): 尝试获取锁,返回值为boolean,未获取到锁,立即返回false,获取到锁,立

    ​ 即返回true。

    tryLock(long timeout, TimeUnit unit):

    指定时间内尝试获取锁,返回值为boolean,若在指定时间内未获取到锁,返回

    false,获取到锁,返回true,优先响应中断。

    金麟岂能忍一世平凡 飞上了青天 天下还依然
  • 相关阅读:
    使用命令行管理virtualBox
    springboot activiti 整合项目框架源码 shiro 安全框架 druid 数据库连接池
    activiti工作流的web流程设计器整合视频教程 SSM 和 独立部署
    java springMVC SSM 操作日志 4级别联动 文件管理 头像编辑 shiro redis
    MVC、MVP、MVVM 模式对比
    GoBelieve IM 消息推送的方案
    Token生成(转载)
    ios的framework合并
    Gobelieve 架构(转载)
    xcode10不兼容问题解决方法,framework编译脚本
  • 原文地址:https://www.cnblogs.com/Auge/p/11759853.html
Copyright © 2020-2023  润新知