Java Executor Service - 线程超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16277191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Executor Service - timeout of thread
提问by sanbhat
While I was exploring ExecutorService
, I encountered a method Future.get()
which accepts the timeout
.
在探索的过程中ExecutorService
,我遇到了一种Future.get()
接受timeout
.
The Java doc of this method says
此方法的 Java 文档说
Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.
如有必要,最多等待给定的计算完成时间,然后检索其结果(如果可用)。
Parameters:
参数:
timeoutthe maximum time to wait
timeout等待的最长时间
unitthe time unit of the timeout argument
unit超时参数的时间单位
As per my understanding, we are imposing a timeout on the callable
, we submit to the ExecutorService
so that, my callable
will interruptafter the specified time(timeout) has passed
根据我的理解,我们正在对 施加超时callable
,我们提交给ExecutorService
以便,我callable
将在指定的时间(超时)过后中断
But as per below code, the longMethod()
seems to be running beyond the timeout(2 seconds), and I am really confused understanding this. Can anyone please point me to the right path?
但根据下面的代码,longMethod()
似乎超出了超时(2 秒),我真的很困惑理解这一点。任何人都可以指出我正确的道路吗?
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Timeout implements Callable<String> {
public void longMethod() {
for(int i=0; i< Integer.MAX_VALUE; i++) {
System.out.println("a");
}
}
@Override
public String call() throws Exception {
longMethod();
return "done";
}
/**
* @param args
*/
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadExecutor();
try {
service.submit(new Timeout()).get(2, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
}
}
采纳答案by Eugene
my callable will interrupt after the specified time(timeout) has passed
我的可调用对象将在指定的时间(超时)过后中断
Not true. The task will continue to execute, instead you will have a null string after the timeout.
不对。该任务将继续执行,而超时后您将获得一个空字符串。
If you want to cancel it:
如果你想取消它:
timeout.cancel(true) //Timeout timeout = new Timeout();
P.S. As you have it right now this interrupt will have no effect what so ever. You are not checking it in any way.
PS 正如您现在拥有的那样,此中断将不会产生任何影响。你没有以任何方式检查它。
For example this code takes into account interrupts:
例如,此代码考虑了中断:
private static final class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
StringBuilder builder = new StringBuilder();
try{
for(int i=0;i<Integer.MAX_VALUE;++i){
builder.append("a");
Thread.sleep(100);
}
}catch(InterruptedException e){
System.out.println("Thread was interrupted");
}
return builder.toString();
}
}
And then:
进而:
ExecutorService service = Executors.newFixedThreadPool(1);
MyCallable myCallable = new MyCallable();
Future<String> futureResult = service.submit(myCallable);
String result = null;
try{
result = futureResult.get(1000, TimeUnit.MILLISECONDS);
}catch(TimeoutException e){
System.out.println("No response after one second");
futureResult.cancel(true);
}
service.shutdown();
回答by rolfl
The timeout on get() is for how long the 'client' will wait for the Future to complete. It does not have an impact on the future's execution.
get() 的超时时间是“客户端”等待 Future 完成的时间。它不会对未来的执行产生影响。
Object result;
int seconds = 0;
while ((result = fut.get.(1, TimeUnit.SECOND)) == null) {
seconds++;
System.out.println("Waited " + seconds + " seconds for future";
}
回答by shazin
my callable will interruptafter the specified time(timeout) has passed
我的可调用对象将在指定的时间(超时)过后中断
The above statement is wrong, Usually Future.get is blocking. Specifying the timeout allows you to use it in a non blocking manner.
上面的说法是错误的,通常 Future.get 是阻塞的。指定超时允许您以非阻塞方式使用它。
This is useful for instance in time critical applications, if you need a result within let's say 2 seconds and receiving after that means you can't do anything with that.
例如,这在对时间要求严格的应用程序中很有用,如果您需要在 2 秒内得到结果,而在此之后接收则意味着您无法对此做任何事情。