---
title: "java Lock 以及lockInterruptibly"
author: "gotowqj"
date: "2014-08-14T10:24:03Z"
tags: ["Java"]
categories: ["编程语言"]
slug: "java-lock-lockinterruptibly"
draft: false
lastmod: "2014-08-14T10:24:03Z"
id: 2103793
url: "https://gotowqj.iteye.com/blog/2103793"
---

## Lock接口的 线程请求锁的 几个方法：

lock(), 拿不到lock就不罢休，不然线程就一直block。 比较无赖的做法。  
tryLock()，马上返回，拿到lock就返回true，不然返回false。 比较潇洒的做法。  
带时间限制的tryLock()，拿不到lock，就等一段时间，超时返回false。比较聪明的做法。

## 下面的lockInterruptibly()就稍微难理解一些。

先说说线程的打扰机制，每个线程都有一个 打扰 标志。这里分两种情况，  
1\. 线程在sleep或wait,join， 此时如果别的进程调用此进程的 interrupt（）方法，此线程会被唤醒并被要求处理InterruptedException；(thread在做IO操作时也可能有类似行为，见java thread api)  
2\. 此线程在运行中， 则不会收到提醒。但是 此线程的 “打扰标志”会被设置， 可以通过isInterrupted()查看并 作出处理。

lockInterruptibly()和上面的第一种情况是一样的， 线程在请求lock并被阻塞时，如果被interrupt，则“此线程会被唤醒并被要求处理InterruptedException”。

## 我写了几个test，验证一下：

1). lock()忽视interrupt(), 拿不到锁就 一直阻塞：

[]()

01. @Test
02. publicvoid test3()throwsException{
03. finalLock lock=newReentrantLock();
04. lock.lock();
05. Thread.sleep(1000);
06. Thread t1=newThread(newRunnable(){
07. @Override
08. publicvoid run(){
09. lock.lock();
10. System.out.println(Thread.currentThread().getName()+" interrupted.");
11. }
12. });
13. t1.start();
14. Thread.sleep(1000);
15. t1.interrupt();
16. Thread.sleep(1000000);
17. }

 

可以进一步在Eclipse debug模式下观察，子线程一直阻塞。

2). lockInterruptibly()会响应打扰 并catch到InterruptedException

[]()

01. @Test
02. publicvoid test4()throwsException{
03. finalLock lock=newReentrantLock();
04. lock.lock();
05. Thread.sleep(1000);
06. Thread t1=newThread(newRunnable(){
07. @Override
08. publicvoid run(){
09. try{
10. lock.lockInterruptibly();
11. }catch(InterruptedException e){
12. System.out.println(Thread.currentThread().getName()+" interrupted.");
13. }
14. }
15. });
16. t1.start();
17. Thread.sleep(1000);
18. t1.interrupt();
19. Thread.sleep(1000000);
20. }

 

3). 以下实验验证：当线程已经被打扰了（isInterrupted()返回true）。则线程使用lock.lockInterruptibly()，直接会被要求处理InterruptedException。

[]()

01. @Test
02. publicvoid test5()throwsException{
03. finalLock lock=newReentrantLock();
04. Thread t1=newThread(newRunnable(){
05. @Override
06. publicvoid run(){
07. try{
08. Thread.sleep(2000);
09. lock.lockInterruptibly();
10. }catch(InterruptedException e){
11. System.out.println(Thread.currentThread().getName()+" interrupted.");
12. }
13. }
14. });
15. t1.start();
16. t1.interrupt();
17. Thread.sleep(10000000);
18. }