我有一个调用Semaphore.tryAcquire(timeout, timeunit)
函数的函数。现在,我想中断此tryAcquire函数,以便调用者函数将引发一些异常。我的代码思路如下:
public void run() throw InterruptedException{
semaphore.tryAcquire(timeout, timeunit);
}
public void interrupt(){
// interrupt my run() function execution so that run() will throw InterruptedException
}
有任何可行的方法吗?
最佳答案
看看this tutorial,它详细介绍了您的确切问题。它的基础:Thread类具有interrupt方法。简单地调用它会导致阻塞操作(例如tryAcquire
)抛出InterruptedException。
static void main(String[] args)
{
Thread child = new Thread(){
public void run()
{
try
{
Thread.sleep(4000);
// or in your case, semaphore.tryAcquire(timeout, timeunit);
}
catch (InterruptedException e)
{
System.out.println("We've been interrupted!");
}
}
}
child.start();
child.interrupt();
}