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.
Java中断机制详解
本文深入探讨了Java中线程的中断机制,特别是如何通过Lock.lockInterruptibly()来避免线程死锁的问题。文章通过示例代码展示了不同情况下线程如何响应中断请求。
1176

被折叠的 条评论
为什么被折叠?



