我正在尝试在番石榴库的帮助下停止/取消线程,但超时。
长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,它也无法正常工作,请对此进行解决。谢谢。
答案 0 :(得分:1)
要响应中断,您对call
的实现必须调用响应中断的方法(例如CountDownLatch.await
),或通过Thread.interrupted
或isInterrupted
手动检查中断