ScheduledThreadPool中的schedule方法

本文介绍了一个使用Java ScheduledExecutorService实现的任务延迟执行示例。通过创建ScheduledThreadPool并使用schedule方法来延迟5秒后执行特定任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

延迟指定时间执行任务的记录

/**
 * for     测试scheduled方法  延迟执行任务的方法
 * get    先执行任务之后的代码,指定时间后执行任务代码(遇见新的线程,只要时间到就执行任务代码)
 * 
 * @author fangguanqgiang
 *
 * 2018年6月7日
 */
public class TestScheduledThreadPool {
public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);
        testTask(pool);
    }


@SuppressWarnings("static-access")
private static void testTask(ScheduledExecutorService pool)
throws InterruptedException {
System.out.println("程序执行的时间:"+new Timestamp(System.currentTimeMillis()));
        pool.schedule(new Runnable() {

@Override
public void run() {
  System.out.println("执行任务的时间:"+new Timestamp(System.currentTimeMillis()));
}
}, 5, TimeUnit.SECONDS);//延迟5秒执行任务
        
        Thread thread = new Thread();
        thread.sleep(6*1000);
        System.err.println("最后一行代码执行的时间:"+new Timestamp(System.currentTimeMillis()));
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值