我正在关注我在网上多次看到的代码组合including examples here on SO等等,但它不会为我编译。
import com.google.common.util.concurrent.SimpleTimeLimiter;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class TimeLimit
{
public static void main(String[] args)
{
SimpleTimeLimiter limiter = new SimpleTimeLimiter();
String result = limiter.callWithTimeout(new Callable<String>()
{
public String call()
{
return longTimeExecutingMethod();
}
}, 3, TimeUnit.SECONDS, false);
}
public static String longTimeExecutingMethod()
{
return "long time executing method";
}
}
我得到的错误是:
Error:(10, 45) java: constructor SimpleTimeLimiter in class com.google.common.util.concurrent.SimpleTimeLimiter cannot be applied to given types;
required: java.util.concurrent.ExecutorService
found: no arguments
reason: actual and formal argument lists differ in length
和
Error:(11, 40) java: method callWithTimeout in class com.google.common.util.concurrent.SimpleTimeLimiter cannot be applied to given types;
required: java.util.concurrent.Callable<T>,long,java.util.concurrent.TimeUnit
found: <anonymous java.util.concurrent.Callable<java.lang.String>>,int,java.util.concurrent.TimeUnit,boolean
reason: cannot infer type-variable(s) T
(actual and formal argument lists differ in length)
对于我尝试创建单线程执行程序的第一个错误:
SimpleTimeLimiter limiter = new SimpleTimeLimiter(Executors.newSingleThreadExecutor());
但这只会导致第一次编译错误改为:
Error:(10, 45) java: SimpleTimeLimiter(java.util.concurrent.ExecutorService) has private access in com.google.common.util.concurrent.SimpleTimeLimiter
答案 0 :(得分:2)
SimpleTimeLimiter limiter = SimpleTimeLimiter.create(executor);