public class ReentrantDemo { //重入锁 保护临界区资源count,确保多线程对count操作的安全性 /*public static ReentrantLock rtlock = new ReentrantLock(); public static int count = 0; Thread t = new Thread(new Runnable() { @Override public void run() { for(int i=0;i<100000;i++){ rtlock.lock(); try{ count++; }finally { rtlock.unlock(); } } } });*/ //重入锁 对于死锁的中断响应 public static ReentrantLock rtlock1 = new ReentrantLock(); public static ReentrantLock rtlock2 = new ReentrantLock(); private int lock; public ReentrantDemo(int lock){ this.lock = lock; } Thread t = new Thread(new Runnable() { @Override public void run() { try{ if(lock == 1){ /* 当两个线程同时通过lock.lockInterruptibly()想获取某个锁时,假若此时线程A获取到了锁, 而线程B只有等待,那么对线程B调用threadB.interrupt()方法能够中断线程B的等待过程 注意是:等待的那个线程B可以被中断,不是正在执行的A线程被中断 */ rtlock1.lockInterruptibly(); try{ Thread.sleep(3000); }catch (InterruptedException e){ } rtlock2.lockInterruptibly(); } else{ rtlock2.lockInterruptibly(); try{ Thread.sleep(500); }catch (InterruptedException e){ } rtlock1.lockInterruptibly(); } }catch (InterruptedException e){ e.getMessage(); }finally { if(rtlock1.isHeldByCurrentThread()) rtlock1.unlock(); if(rtlock2.isHeldByCurrentThread()) rtlock2.unlock(); System.out.println("线程退出:" + Thread.currentThread().getName()); } } }); public static void main(String[] args) throws InterruptedException{ /*ReentrantDemo rtd = new ReentrantDemo(); Thread t1 = new Thread(rtd.t); Thread t2 = new Thread(rtd.t); Thread t3 = new Thread(rtd.t); t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join(); System.out.println(count);*/ /* 避免死锁的方法:1. 外部方法,通过中断避免死锁 2. 锁申请限时等待 3. ReentrantLock.tryLock() */ ReentrantDemo rtd1 = new ReentrantDemo(1); ReentrantDemo rtd2 = new ReentrantDemo(1); Thread t1 = new Thread(rtd1.t); Thread t2 = new Thread(rtd2.t); t1.start(); t2.start(); Thread.sleep(1000); //t2中断 释放资源 t2.interrupt(); } }