51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

Java延时执行

为了实现Java的延迟执行,常用的方法包括使用Thread。.sleep()使用Timer类,或使用ScheduledExecutorService接口的方法。

使用Thread.sleep()方法 {#title-1}

Thread.sleep()方法是一种静态方法,用于暂停执行当前线程一段时间,将CPU交给其他线程。使用这种方法实现延迟执行非常简单,只需将延迟时间作为参数传入即可。

public class TestDelay {
    public static void main(String[] args) {
        System.out.println("Start: " + System.currentTimeMillis());
        try {
            Thread.sleep(5000);   //延时5秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("End: " + System.currentTimeMillis());
    }
}

注意,Thread.sleep()方法可以被其它线程中断,从而提前结束暂停。

使用Timer类。 {#title-2}

Timer类可以用来安排一次执行任务或重复固定执行。通常需要配合TimerTask类使用Timer来实现延迟执行。以下是一个简单的例子:

import java.util.Timer;
import java.util.TimerTask;

public class TimerTaskTest {
    public static void main(String[] args) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Task executed");
            }
        };

        Timer timer = new Timer();
        timer.schedule(task, 5000);    // 在5秒内执行task
    }
}

使用ScheduledExecutorService接口接口 {#title-3}

ScheduledExecutorService接口是ExecutorService的子接口,增加了对延迟执行或定期执行任务的支持。ScheduledExecutorService提供了错误处理、结果获取等更强大的功能。

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorServiceTest {
    public static void main(String[] args) {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        executor.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("Task executed");
            }
        }, 5, TimeUnit.SECONDS);    // 五秒钟后执行任务
        executor.shutdown();
    }
}

Java中的延迟执行操作可以通过以上三种方法轻松实现。

赞(2)
未经允许不得转载:工具盒子 » Java延时执行