应用程序中经常需要在后台运行某些特定任务以在一定间隔内完成某些工作。 该示例可以是,服务在后台运行以清理应用程序,就像我们有Java Garbage集合一样。
在本文中,我将向您展示3种不同的方法来实现这一目标
他们如下
- 使用简单的线程
- 使用TimerTask
- 使用ScheduledExecutorService
使用简单的线程
这非常简单,它创建了一个简单的线程,使用while循环使其永远运行,并利用sleep方法放置两次运行之间的间隔。
这是实现它的快捷方法
以下是此代码。
public class Task1 {
public static void main(String[] args) {
// run in a second
final long timeInterval = 1000;
Runnable runnable = new Runnable() {
public void run() {
while (true) {
// ------- code for task to run
System.out.println("Hello !!");
// ------- ends here
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e)