gpt4 book ai didi

java - 时间表和可调用

转载 作者:行者123 更新时间:2023-12-02 08:08:43 25 4
gpt4 key购买 nike

我正在尝试在主要 Activity 中使用 ScheduledExecutorService,其中有一些用户界面控件。在某些情况下,我希望将其中一个调用的方法延迟一秒:

ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(5);

ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(new Callable() {
public Object call() throws Exception {
stopSomething();
}
},
1,
TimeUnit.SECONDS);

try {
scheduledFuture.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

scheduledExecutorService.shutdown();

这样的代码 fragment 可以在程序的另一部分工作,所以我知道这个解决方案的轮廓至少在那里工作。但是在主要 Activity 以及我尝试过的程序的其他部分(我可以实际使用它的地方),Eclipse 不断发现一些问题:

ScheduledFuture ScheduledFuture = ScheduledExecutorService.schedule(new Callable() { 公共(public)对象调用()抛出异常{

如果编译错误不在 Object call() throws Exception 上,则它在 schedule(new Callable()) 上,就像现在一样。

schedule 下的红线是“ScheduledExecutorService 类型中的方法 Schedule(Runnable, long, TimeUnit) 不适用于参数 (new Callable(){}, int, TimeUnit)”

Callable 下的红线是“Callable 无法解析为类型”

(也许.schedule(Runnable任务,长延迟,TimeUnit timeunit)在这里使用是一个更好的方法?如果是这样,什么会导致错误“ScheduledExecutorService类型中的方法schedule(Runnable,long,TimeUnit)是不适用于参数 (new Callable(){}, int, TimeUnit)"?这想要什么?它是如何组成的?)

最佳答案

您正在使用的 Callable 的返回类型是 Object,但您没有返回任何内容

Callable callable = new Callable() {
public Object call() throws Exception {
stopSomething();
// missing return statement
};

如果您不需要返回任何内容,并且不抛出任何已检查的异常,您可以使用:

Runnable runnable = new Runnable() {
public void run() {
stopSomething();
};

关于java - 时间表和可调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7778075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com