http://www.iteedu.com/plang/java/superjava/threadsafe/lockInterruptibly.php
以前我们用
synchronized (mutex) {
。。。。。。。
}
进行同步时必须等待别的线程释放锁后才能进入同步块,现在问题时当太长时间等待时不想再等了,怎么办?
ReentrantLock为我们实现了中断等待的方法。
class SampleSupport1 extends SampleSupport {
private final ReentrantLock lock = new ReentrantLock();
public void doSomething() throws InterruptedException {
lock.lockInterruptibly();
System.out.println(Thread.currentThread().getName());
// try {
// lock.lockInterruptibly();
// } catch (InterruptedException e) {
// //做一些其它的事,不结束线程
// }
System.out.println(Thread.currentThread().getName() + " will execute counter++.");
startTheCountdown();
try {
counter++;
}
finally {
lock.unlock();
}
}
}
外部对他的引用进行b.interrupt();