固定时间后中止循环 [英] Abort loop after fixed time
问题描述
我有一个线程,其中我有一个无限循环,做一些网络的东西。看来,我没有得到一个响应,每次我这样做,所以线程挂起几秒钟,这导致我的软件严重的问题。我需要的是某种最后期限的循环,如果它需要更多的时间(例如100ms)再次重新启动。
I hava a thread in which I have an infinite loop, doing some network stuff. It appears that I don't get a response every time i'm doing this so the thread hangs for several seconds which causes serious problems to my software. What I need is some kind of "deadline" for the loop, if it takes more then (e.g. 100ms) restart again.
private boolean active = true;
public void run(){
while(active){
//some network stuff e.g:
dnshandler.reverselookup("8.8.8.8");
}
}
...
任何想法如何处理这个?
Any Ideas how to handle this?
更新:
我推荐使用单独的主题。实际上,我使用一个Callable因为我需要一个返回值。
Update: I handeled it with a seperate Thread as suggested. Actually I used a Callable becouse I need a return value.
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
try {
List<Future<String>> results = executor.invokeAll(Arrays.asList(new CallableClass()), 500), TimeUnit.MILLISECONDS);
for (Future<String> current : results) {
if (!current.isCancelled()) {
someValue = current.get();
} else {
// timeout
executor.shutdownNow();
}
}
} catch (Exception e) {
//handle it!
e.printStackTrace();
}
但我现在面临的问题是,执行器.shutdownNow()
不会终止挂起的可调任务(这是根据文档的正确行为)。有没有办法杀死一个执行器任务? (我知道这不是一个干净的解决方案,但一些请求由一个库处理)
But the problem I face now is, that executor.shutdownNow()
isn't terminating the hanging Callable task(which is the correct behaviour according to the Documentation). Is there a way to kill an executor task? (I know this is not a clean solution but some of the requests are handled by a library)
推荐答案
并将其运行几秒钟,例如:
You can put your networking stuff into a separate thread and run it for a couple of seconds for instance:
int timeoutTime = ...
Runnable networkingStuff = ... // put the networking in here
Thread thread =new Thread(networkingStuff);
thread.start();
try {
thread.join(timeoutTime);
if(thread.isAlive()) {
thread.interrupt();
}
} catch (InterruptedException e) {
// catch here the interruption
}
这篇关于固定时间后中止循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!