我有一个调用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
}有没有可能做到这一点?
发布于 2016-05-01 15:59:13
看一看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();
}https://stackoverflow.com/questions/36964222
复制相似问题