gpt4 book ai didi

java - 在此示例代码中怎么可能实例化接口(interface)?

转载 作者:行者123 更新时间:2023-12-01 12:10:13 25 4
gpt4 key购买 nike

我正在阅读的手册包含此示例,其中 ScheduledExecutorService正在创建中。但是,API 显示 ScheduledExecutorService是一个接口(interface),而不是一个类。那么它怎么可能被实例化呢?

下面是示例代码:

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import static java.util.concurrent.TimeUnit.*;

class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);

public void beepForAMinute() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
}
};

final ScheduledFuture<?> future =
scheduler.scheduleAtFixedRate(beeper, 250, 250, MILLISECONDS);
scheduler.schedule(
new Runnable() {
public void run() {
future.cancel(true);
}
}, 3, SECONDS);
while (!future.isDone()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
scheduler.shutdown();
}

public static void main(String[] args) {
BeeperControl bc = new BeeperControl();
bc.beepForAMinute();
}
}

最佳答案

Executors.newSceduledThreadPool(int)是一个工厂方法,它返回一个实现 ScheduledExecutorService 接口(interface)的类。

根据 GrepCode:

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}

所以这里它返回实现 ScheduledExecutorService 接口(interface)的 ScheduledThreadPoolExecutor 的新实例。

关于java - 在此示例代码中怎么可能实例化接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27322856/

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