gpt4 book ai didi

java - 方法返回可运行对象

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

我可以用 Java 做这样的事情吗:

 protected Runnable getRunnable(final int seconds) {
Runnable runnable = new Runnable() {
public void run() {
sendData();
try {
Thread.sleep(seconds * 1000);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
};
return runnable;
}

然后:

protected void startTimer(int seconds) throws InterruptedException,NullPointerException {
Thread thread = new Thread(getRunnable(seconds));
thread.start();
}

上述过程安全吗?

最佳答案

在评论中你说

All I'm trying to do is to execute sendData() method every a specific amount of seconds(i.e. every 15 seconds)

然后使用内置计时器来为您组织,例如:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable r = new Runnable() {
@Override
public void run() {
sendData();
}
};
ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(r, 0, 15, TimeUnit.SECONDS);

//when you want to cancel the scheduled task
future.cancel(true);

//and before you leave your program, don't forget to call:
scheduler.shutdown();

关于java - 方法返回可运行对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14215424/

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