`

Re entrantLock usage

阅读更多

 a thread can be really interrupted by aThread.interrupt() only under 1 situation -- in blocked status wrapped with catch(InterruptedException e) {...}. Precisely,

 

 a) aThread.sleep();

 b) aObject.wait();

 c) BlockingQueue operations;

 d) Lock.lockInterruptibly();

 

Regarding d). When a thread is waiting outside of some lock, previously, you can't interrupt it, the thread will just block there if he can not get the lock --- dead lock.

 

In Java 5, Lock.lockInterruptibly() needs to be wrapped with InterruptedException, which means you can save the thread from stupid waiting.

 

=====Code example ======

 

public static void main(String[] args)

{

Thread i1 = new Thread(new RunIt3());

Thread i2 = new Thread(new RunIt3());

i1.start();

i2.start();

i2.interrupt();

}

 

 

class RunIt3 implements Runnable

{

private static Lock lock = new ReentrantLock();

 

public void run()

{

 

try

{

lock.lock();

//lock.lockInterruptibly(); ---- c)

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

TimeUnit.SECONDS.sleep(20); ----- b)

lock.unlock();

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

}

catch (InterruptedException e)

{

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

}

 

}

}

 

---Output---

Thread-0 running  ----  a)

Thread-0 finished

Thread-1 running

Thread-1 interrupted

 

Explain:

a) Actually at here, thread1 has already been interrupted. But thread1 has to wait 20 seconds later, till thread0 has finished running, and thread1 goes to place b), at that place, thread1 can goto catch block! That’s quite late!

 

 

If you change from lock.lock() to lock.lockInterruptibly()

 

---Output---

Thread-0 running

Thread-1 interrupted

Thread-0 finished

 

Because c) has been monitored with InterruptedException, when thread0 is working, thread1 is waiting outside of lock, if you interrupt thread1, thread1 will immediately goes to catch block.

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics