我正在尝试编写一个用于轮询的守护线程,它将每“3”秒轮询一次。我见过3种方法。我不知道该去哪一个?我想知道性能注意事项。哪一个可能是一致的并且会占用更小的内存块?
方法1:使用TimerTask(不打算使用这个)
new Timer().scheduleAtFixedRate(task, firstTime, period)
方法 2:使用 ScheduledExecutorService
方法 3:使用 Thread.sleep() ....
如果我归结为这样的代码:
方法#2
public class Test {
static TimerTask timerTask = new TimerTask() {
@Override
public void run() {
// Do polling & Other business logic
System.out.println("=="+new Date());
}
};
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors
.newSingleThreadScheduledExecutor();
scheduler.scheduleWithFixedDelay(timerTask, 0, 3, TimeUnit.SECONDS);
}
}
为了
方法#3
public class Test {
static Runnable task = new Runnable() {
@Override
public void run() {
while (true) {
try {
// Do polling & Other business logic
System.out.println("**"+new Date());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
public static void main(String[] args) {
new Thread(task).start();
}
}
据我了解,与普通线程相比,线程池是一种重物。我想知道使用这两种方法的优缺点是什么?
提前致谢。
问候, 乙脑