有没有一种方法可以完全停止java中的任务?
如果任务没有在要求的时间内完成,我希望任务以预定的时间间隔和超时运行,继续进一步迭代 我已经看了以下答案,但它没有解决我的问题 考虑以下情况有没有一种方法可以完全停止java中的任务?,java,multithreading,Java,Multithreading,如果任务没有在要求的时间内完成,我希望任务以预定的时间间隔和超时运行,继续进一步迭代 我已经看了以下答案,但它没有解决我的问题 考虑以下情况 BasicThreadFactory collectionFactory = new BasicThreadFactory.Builder() .namingPattern("CollectionExecutor-%d") .build(); // thread pool size is
BasicThreadFactory collectionFactory = new BasicThreadFactory.Builder()
.namingPattern("CollectionExecutor-%d")
.build();
// thread pool size is set 2
// 1-for scheduler thread which runs task and tracks timeout
// 2-for task itself
ScheduledExecutorService collectionExecuter =
Executors.newScheduledThreadPool(2, collectionFactory);
// fires collection every minute and if it is in between execution during
// scheduled time then waits for completion and executes immediately
// after it
//my task:
Runnable runnable= new Runnable() {
@Override
public void run() {
try {
System.out.println("Executed started");
Thread.sleep(2000);
System.out.println("Executed after .get method call.");
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(20000);
System.out.println("Executed even after .cancel method " +
"call (I want this to avoid this.)");
} catch (Exception e) {
e.printStackTrace();
}
}
};
以上任务应以3秒的间隔运行,如果超过1秒,则停止……认为在单次尝试catch块中不可能有完整的任务,现在我如何阻止任务在下一次休眠中继续等待(20000)并继续下一次迭代。
collectionExecuter.scheduleAtFixedRate(new Runnable() {//scheduler thread
@Override
public void run() {
try {
Future<?> future = collectionExecuter.submit(runnable);
try {
future.get(1, TimeUnit.SECONDS);
} catch (Exception e) {
future.cancel(true);
System.out.println("Collection thread did not " +
"completed in 1 Sec.Thread Interrupted");
}
} catch (Exception e) {
System.out.println("Unable to start Collection Thread");
}
}
}, 0, 3, TimeUnit.SECONDS);
}
collectionExecuter.scheduleAtFixedRate(新的Runnable(){//调度程序线程
@凌驾
公开募捐{
试一试{
Future=collectionExecuter.submit(可运行);
试一试{
future.get(1,TimeUnit.SECONDS);
}捕获(例外e){
future.cancel(true);
System.out.println(“收集线程没有”+
“在1秒内完成,线程中断”);
}
}捕获(例外e){
System.out.println(“无法启动收集线程”);
}
}
},0,3,时间单位为秒);
}
让任务在长时间睡眠后检查一些标志,如果该标志指示任务应该停止,则返回该标志。为什么其他问题没有帮助?我在这里看到了几个可以实现您所希望的行为的答案。@Thomas sleep可能是一个读取延迟为20秒的DB调用。如果您的问题是由阻止IO调用引起的,那么您的问题应该是关于异步IO实现的,而不是关于杀死线程的。请看这个例子:所有InterruptedException捕获都应该正确停止线程,重新启动currentThread.interrupt(),或者在您的情况下,直接返回。当捕捉到该异常时,也会捕捉到中断信号。这是一个很好的答案: