java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java延时执行

Java延时执行的三种实现方式

作者:python100

本文主要介绍了Java延时执行的三种实现方式,主要包括了Thread.sleep()方法,.sleep()使用Timer类或使用ScheduledExecutorService接口,感兴趣的可以了解一下

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

使用Thread.sleep()方法

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类。

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接口接口

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延时执行的三种实现方式的文章就介绍到这了,更多相关Java延时执行内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文