`

java Lock 以及lockInterruptibly

阅读更多

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(), 拿不到锁就 一直阻塞:

  1. @Test
  2. publicvoid test3()throwsException{
  3.     finalLock lock=newReentrantLock();
  4.     lock.lock();
  5.     Thread.sleep(1000);
  6.     Thread t1=newThread(newRunnable(){
  7.         @Override
  8.         publicvoid run(){
  9.             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

  1. @Test
  2. publicvoid test4()throwsException{
  3.     finalLock lock=newReentrantLock();
  4.     lock.lock();
  5.     Thread.sleep(1000);
  6.     Thread t1=newThread(newRunnable(){
  7.         @Override
  8.         publicvoid run(){
  9.             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。

  1. @Test
  2. publicvoid test5()throwsException{
  3.     finalLock lock=newReentrantLock();
  4.     Thread t1=newThread(newRunnable(){
  5.         @Override
  6.         publicvoid run(){
  7.             try{
  8.                 Thread.sleep(2000);
  9.                 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. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics