我试图在 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 也不起作用,请帮我解决这个问题。谢谢。
最佳答案
要响应中断,您的 call
实现必须调用响应中断的方法(例如 CountDownLatch.await
)或通过 手动检查中断Thread.interrupted
或 isInterrupted
。
关于java - TimeLimiter 的 callWithTimeout 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57405699/