TimeLimiter的callWithTimeout不起作用?

时间:2019-08-08 05:31:33

标签: java concurrency guava

我正在尝试在番石榴库的帮助下停止/取消线程,但超时。

长callTimeout = 1公升;

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,它也无法正常工作,请对此进行解决。谢谢。

1 个答案:

答案 0 :(得分:1)

  

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手动检查中断