Difference lock () and lockInterruptibly () of

lock and compare the difference lockInterruptibly that:
lock priority to acquire the lock, the lock is to be acquired success only in response to interrupts.
lockInterruptibly priority interrupt response, rather than in response to the lock over normal or reentrant acquisition.

Detailed differences:

ReentrantLock.lockInterruptibly allow Thread.interrupt method while waiting for waiting for the other thread to thread calls the interrupt latency of waiting threads and direct return, then do not get a lock, but will throw an InterruptedException. ReentrantLock.lock method does not allow Thread.interrupt interruption, even if the detected Thread.isInterrupted, the same will continue to try to acquire the lock fails to continue to sleep. In just the last to acquire the lock after the success of the current thread is set to interrupted state, then interrupt thread.

Look at the test code is as follows:

 
  1. class MyThread05 extends Thread{

  2. public void test3() throws Exception{

  3. final Lock lock = new ReentrantLock();

  4. lock.lock();

  5. Thread.sleep(1000);

  6. Thread t1 = new Thread(new Runnable(){

  7. @Override

  8. public void run() {

  9. lock.lock();

  10. // try {

  11. // lock.lockInterruptibly();

  12. // } catch (InterruptedException e) {

  13. // // TODO Auto-generated catch block

  14. // e.printStackTrace();

  15. // }

  16. System.out.println(Thread.currentThread().getName()+" interrupted.");

  17. }

  18. });

  19. t1.start();

  20. Thread.sleep(1000);

  21. t1.interrupt();

  22. Thread.sleep(1000000);

  23. }

  24. }

As used herein, the lock () method, the method is performed in the main routine test3 () Press found that even executed interrupt () method is not a reaction.

The comments in the code cancel, we will find that the program requires to capture the exception

Published 776 original articles · won praise 50 · Views 150,000 +

Guess you like

Origin blog.csdn.net/weixin_44018338/article/details/105228295