首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何中断Java Semaphore.tryAcquire函数

如何中断Java Semaphore.tryAcquire函数
EN

Stack Overflow用户
提问于 2016-05-01 15:31:41
回答 1查看 1.1K关注 0票数 2

我有一个调用Semaphore.tryAcquire(timeout, timeunit)函数的函数。现在我想中断这个tryAcquire函数,这样调用者函数就会抛出一些异常。我的代码思路如下:

代码语言:javascript
复制
public void run() throw InterruptedException{
    semaphore.tryAcquire(timeout, timeunit);
}

public void interrupt(){
   // interrupt my run() function execution so that run() will throw InterruptedException
}

有没有可能做到这一点?

EN

回答 1

Stack Overflow用户

发布于 2016-05-01 15:59:13

看一看this tutorial,它非常详细地介绍了你的问题。它的基础知识: Thread类有一个interrupt方法。简单地调用它将导致阻塞操作,如tryAcquire,抛出InterruptedException。

代码语言:javascript
复制
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();
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36964222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档