【发布时间】:2009-03-12 01:55:51
【问题描述】:
我正在尝试将代码从使用 java timers 移植到使用 scheduledexecutorservice
我有以下用例
class A {
public boolean execute() {
try {
Timer t = new Timer();
t.schedule (new ATimerTask(), period, delay);
} catch (Exception e) {
return false;
}
}
}
class B {
public boolean execute() {
try {
Timer t = new Timer();
t.schedule (new BTimerTask(), period, delay);
} catch (Exception e) {
return false;
}
}
}
我是否应该将 A 类和 B 类中的 Timer 实例替换为 ScheduledExecutorService 并将 ATimerTask 和 BTimerTask 类设为 Runnable 类,例如
class B {
public boolean execute() {
try {
final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
scheduler.scheduleWithFixedDelay (new BRunnnableTask(), period, delay);
} catch (Exception e) {
return false;
}
}
}
这对吗?
编辑:移植的主要动机之一是因为 TimerTask 中抛出的运行时异常会杀死一个线程并且无法进一步安排它。我想避免这种情况,这样即使我有运行时异常,线程也应该继续执行而不是停止。
【问题讨论】:
标签: java timer executorservice