2010年2月19日星期五

[转]lockInterruptibly 和lock的区别


参考 
http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/util/concurrent/locks/ReentrantLock.html#lockInterruptibly(); 
http://tomboxfan.javaeye.com/blog/368270; 

lockInterruptibly 与 lock比较区别在于 
lockInterruptibly 优先考虑响应中断,而不是响应锁定的普通获取或重入获取 
Java代码 
  1. package test;  
  2.   
  3. import java.util.concurrent.TimeUnit;  
  4. import java.util.concurrent.locks.Lock;  
  5. import java.util.concurrent.locks.ReentrantLock;  
  6.   
  7. public class TTTT {  
  8.     public static void main(String[] args){  
  9.   
  10.         Thread i1 = new Thread(new RunIt3());  
  11.         Thread i2 = new Thread(new RunIt3());  
  12.         i1.start();  
  13.         i2.start();  
  14.         i2.interrupt();  
  15.     }  
  16.   
  17. }  
  18.   
  19. class RunIt3 implements Runnable{  
  20.   
  21.     private static Lock lock = new ReentrantLock();  
  22.     public void run(){  
  23.         try{  
  24.             //---------------------------------a  
  25.             lock.lock();  
  26.             //lock.lockInterruptibly();   
  27.               
  28.               
  29.             System.out.println(Thread.currentThread().getName() + " running");  
  30.             TimeUnit.SECONDS.sleep(20);  
  31.             lock.unlock();  
  32.             System.out.println(Thread.currentThread().getName() + " finished");  
  33.         }  
  34.         catch (InterruptedException e){  
  35.             System.out.println(Thread.currentThread().getName() + " interrupted");  
  36.   
  37.         }  
  38.   
  39.     }  
  40. }  


如果a处 是lock.lock(); 
输出 
Thread-0 running 
(这里休眠了20s) 
Thread-0 finished 
Thread-1 running 
Thread-1 interrupted 


============================ 

如果a处是lock.lockInterruptibly() 
Thread-0 running 
Thread-1 interrupted 
(这里休眠了20s) 
Thread-0 finished 
========================= 

如果a处是lock.tryLock(); 


Thread-1 running 
Thread-0 running 
(这里休眠了20s) 
Thread-1 finished 
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException 
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(Unknown Source) 
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(Unknown Source) 
at java.util.concurrent.locks.ReentrantLock.unlock(Unknown Source) 
at test.RunIt3.run(TTTT.java:32) 
at java.lang.Thread.run(Unknown Source) 


========================= 

如果a处是lock.tryLock(10,TimeUnit.SECONDS); 

Thread-0 running 
(这里休眠了10s) 
Thread-1 running 

(这里休眠了10s) 
Thread-0 finished 
(这里休眠了10s) 
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException 
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(Unknown Source) 
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(Unknown Source) 
at java.util.concurrent.locks.ReentrantLock.unlock(Unknown Source) 
at test.RunIt3.run(TTTT.java:32) 
at java.lang.Thread.run(Unknown Source) 

没有评论: