gpt4 book ai didi

java - 单次后台线程,避免连接?

转载 作者:行者123 更新时间:2023-12-01 07:11:01 28 4
gpt4 key购买 nike

简单的问题,此代码是否有效,并且不会留下任何类型的资源泄漏:

    // code...
final int delaySecs = 60;
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(delaySecs * 1000);
// code to do whatever delayed single-shot action
} catch (InterruptedException ex) { /* skip action */ }
}
}).start();
// more code...

如果它无效,我应该使用这样的 Thread 子类来启用 setDaemon(true) 调用:

class DaemonThread extends Thread {
public DaemonThread(Runnable target) {
super(target);
setDaemon(true);
}
}

还是别的什么?

最佳答案

Java 从 1.5 开始就为您的用例提供了特定的支持,因此最好建议您使用它:

ScheduledExecutorService s = Executors.newScheduledThreadPool(1);
s.schedule(new Runnable() { ...my task, no Thread.sleep()... },
1, TimeUnit.MINUTES);
s.shutdown();

这将实现适当的延迟并负责事后的清理。

关于java - 单次后台线程,避免连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14232247/

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