java - TimeLimiter 的 callWithTimeout 不起作用?

标签 java concurrency guava

我试图在 Guava 库的帮助下停止/取消我的线程,但它不起作用。

长callTimeout = 1L;

ExecutorService callTimeoutPool= Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("name").setDaemon(true).build());
LOGGER.log(Level.INFO, "[ TimeoutImpl : timedCall ] currentThread name = {0}", new Object[]{Thread.currentThread().getName()});

try
{
     new SimpleTimeLimiter().callWithTimeout(new Callable(){
     @Override
     public Object call()
     {
          int i=0;
          while(true)
          {
               System.out.println(i++);
               if(false)
                    break;
               }
               return true;
               }
           }, callTimeout, TimeUnit.MILLISECONDS, true);
}
catch(InterruptedException e)
{
     LOGGER.log(Level.SEVERE, "[ TimeoutImpl : timedCall ]  InterruptedException" ,e );
     Thread.currentThread().interrupt();
     callTimeoutPool.shutdownNow();
}
catch(Exception e)
{
     LOGGER.log(Level.SEVERE, "[ TimeoutImpl : timedCall ]  Exception" ,e );
     Thread.currentThread().interrupt();
     callTimeoutPool.shutdownNow();
}

我尝试了 Future.cancel 也不起作用,请帮我解决这个问题。谢谢。

最佳答案

Interruption is a cooperative mechanism. When one thread interrupts another, the interrupted thread does not necessarily stop what it is doing immediately.

要响应中断,您的 call 实现必须调用响应中断的方法(例如 CountDownLatch.await)或通过 手动检查中断Thread.interruptedisInterrupted

关于java - TimeLimiter 的 callWithTimeout 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57405699/

相关文章:

Python - 公认的货币计算技术是什么?

java - Spring 秒表并发

java - 在java中实现一个懒惰的供应商

java - Google Guava 的 CacheLoader loadAll() 方法实现问题

幕后的Java 8方法引用

java - [Ljava.lang.String;@输出错误

java - 奇怪的 wav 文件。我可以使用什么过滤器?

java - 在 Spring 中使用 AuthenticationSuccessHandler 重定向登录页面

c++ - asio::strand 的拷贝是否会创建一个新的执行程序?

java - 如何将条目填充到加载缓存 Guava 中?