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.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值