JAVA ReentrantLock的使用
源码如下
对比synchronized,synchronized使用时会显示的指定一个对象(方法为调用对象,代码块会需要对象作为参数),来获取一个对象的独占锁
而ReentrantLock可能就是使用的ReentrantLock对象的独占锁来实现锁的功能,所以不同线程要用同一个ReentrantLock对象来互斥
public static void main(String[] args){ doSync(); } private static void doSync() { MyThread myThread = new MyThread(); new Thread(myThread).start(); Thread tt = new Thread(myThread); tt.start(); try { Thread.sleep(1000, 0); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("try interuppt "); tt.interrupt(); } class MyThread implements Runnable{ private ReentrantLock lock = new ReentrantLock(); //用同一个lock对象来获取锁,实现互斥,申请的就是lock的锁 @Override public void run() { try { System.out.println("try to wait"); lock.lockInterruptibly(); Thread.sleep(5000); // this.wait(); System.out.println("after wait"); lock.unlock(); } catch (InterruptedException e) { System.out.println("recv interrupt"); } } }
输出:
try to wait try to wait try interuppt recv interrupt after wait