简单的问题,此代码是否有效,并且不会留下任何类型的资源泄漏:
// 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/