lock、tryLock和lockInterruptibly的差別
lock():若lock被thread A取得,thread B会进入block状态,直到取得lock;
tryLock():若当下不能取得lock,thread就会放弃,可以设置一个超时时间参数,等待多久获取不到锁就放弃;
lockInterruptibly():跟lock()情況一下,但是thread B可以通过interrupt中断,放弃继续等待锁
lock 与 lockInterruptibly比较区别在于:lock 优先考虑获取锁,待获取锁成功后,才响应中断,而lockInterruptibly 优先考虑响应中断
ReentrantLock.lockInterruptibly允许在等待时由其它线程调用等待线程的Thread.interrupt方法来中断等待线程的等待而直接返回,这时不用获取锁,而会抛出一个InterruptedException
ReentrantLock.lock方法不允许Thread.interrupt中断,即使检测到Thread.isInterrupted,一样会继续尝试获取锁,失败则继续休眠。只是在最后获取锁成功后再把当前线程置为interrupted状态,然后再中断线程
public class LockDemo { private ReentrantLock lock = new ReentrantLock(); public static void main(String[] args) throws InterruptedException { final LockDemo lockDemo = new LockDemo(); Thread threada = new Thread("Thread A") { @Override public void run() { lockDemo.doSomeThing3(Thread.currentThread()); } }; threada.start(); Thread threadb = new Thread("Thread B") { @Override public void run() { lockDemo.doSomeThing3(Thread.currentThread()); } }; threadb.start(); //threadb.interrupt(); } public void doSomeThing1(Thread thread) { lock.lock(); try { System.out.println(thread.getName() + "得到了锁."); Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println(thread.getName() + "释放了锁."); lock.unlock(); } } public void doSomeThing2(Thread thread) { if (lock.tryLock()) { try { System.out.println(thread.getName() + "得到了锁."); Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println(thread.getName() + "释放了锁."); lock.unlock(); } } else { System.out.println(thread.getName() + "获取锁失败."); } } public void doSomeThing3(Thread thread) { try { lock.lockInterruptibly(); System.out.println(thread.getName() + " 得到了锁."); Thread.sleep(6000); } catch (InterruptedException e1) { e1.printStackTrace(); System.out.println(thread.getName() + " interrupted."); } finally { System.out.println(thread.getName() + " 释放了锁."); lock.unlock(); } } }