简单的问题是,此代码是否有效,并且不会留下任何类型的资源泄漏:
// 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);
}
}
还是其他什么?
答案 0 :(得分:4)
自1.5以来,Java为您的用例提供了特定支持,因此建议您最好使用它:
ScheduledExecutorService s = Executors.newScheduledThreadPool(1);
s.schedule(new Runnable() { ...my task, no Thread.sleep()... },
1, TimeUnit.MINUTES);
s.shutdown();
这将实现适当的延迟并在事后进行清理。
答案 1 :(得分:3)
为什么不只是实例化Thread
,在其上调用setDaemon()
然后通过start()
调用?我认为你不需要Thread
子类。
e.g。
Thread t = ...
t.setDaemon(true);
t.start();
答案 2 :(得分:1)
最好的方法是将应该执行的任何逻辑包装到Runnable中,并将执行保留给ExecutorService。
如果有
,Executor将负责停止/重用ThreadsMyRunnable runnable = new MyRunnable();
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(runnable);
通过这种方式,您可以将程序逻辑与执行/生命周期管理分开。执行程序还能够处理线程中的异常/中断。这将允许您在不打开新线程的情况下重新启动后台逻辑。