Java多线程锁的知识实例讲解
Lock Lock提供了与synchronized类似的同步功能,只是在显式的获取和释放锁,因此有了锁获取和释放的可操作性、可中断的获取锁以及超时获取锁等多种同步特性。 代码实例: Lock lock = new ReentrantLock(); lock.lock(); try{ }finally{ lock.unlock(); } 特性 尝试非阻塞地获取锁:当前线程尝试获取锁,如果这一时刻锁没有被其它线程获取到,则成功获取并持有锁; 能被中断地获取锁:获取到的锁的线程能够响应中断,当获取到锁的线程被中断时,中断异常将会抛出,同时锁被释放; 超时获取锁:在指定时间后获取锁,如果时间到了无法获取,则返回 队列同步器 队列同步器是用来构建锁或其它同步 组件 的基础框架 它使用一个 int变量表示同步状态,通过内置的FIFO队列来完成资源获取线程的排队工作 重写同步器指定方法是,需要使用以下 3个方法访问或修改同步状态 getState():获取当前同步状态 setState(int newState):设置当前同步状态 compareAndSetState(int expect, int update):使用CAS设置当前状态,保证状态设置原子性 重入锁 ReentrantLock:支持重进入的锁,可以支持一个线程对资源的重复加锁,同时还支持获取锁时的公平和非公平性选择。