ScheduledExecutorService接口使用
来源:互联网 发布:java float 编辑:程序博客网 时间:2024/05/22 16:55
- schedule(task,initDelay):安排所提交的Callable或Runnable任务在initDelay指定的时间后执行。
- scheduleAtFixedRate():安排所提交的Runnable任务按指定的间隔重复执行
- scheduleWithFixedDelay():安排所提交的Runnable任务在每次执行完后,等待delay所指定的时间后重复执行。代码:ScheduleExecutorService的例子
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;public class ScheduledExecutorServiceTest
{
public static void main(String[] args) throws InterruptedException,ExecutionException
{
//*1
ScheduledExecutorService service=Executors.newScheduledThreadPool(2);
//*2
Runnable task1=new Runnable()
{
public void run()
{
System.out.println("Taskrepeating.");
}
};
//*3
final ScheduledFuture future1=service.scheduleAtFixedRate(task1,0,1,TimeUnit.SECONDS);
//*4
ScheduledFuture future2=service.schedule(new Callable()
{
public String call()
{
future1.cancel(true);
return "taskcancelled!";
}
},10,TimeUnit.SECONDS);
System.out.println(future2.get());
//*5
service.shutdown();
}
}这个例子有两个任务,第一个任务每隔一秒打印一句“Taskrepeating”,第二个任务在5秒钟后取消第一个任务。
*1:初始化一个ScheduledExecutorService对象,这个对象的线程池大小为2。*2:用内函数的方式定义了一个Runnable任务。*3:调用所定义的ScheduledExecutorService对象来执行任务,任务每秒执行一次。能重复执行的任务一定是 Runnable类型。注意我们可以用TimeUnit来制定时间单位,这也是Java5.0里新的特征,5.0以前的记时单位是微秒,现在可精确到奈秒。*4:调用ScheduledExecutorService对象来执行第二个任务,第二个任务所作的就是在5秒钟后取消第一个任务。*5:关闭服务。
- ScheduledExecutorService接口使用
- ScheduledExecutorService接口
- ScheduledExecutorService接口的学习和使用
- 使用ScheduledExecutorService接口实现Web轮询项目
- ScheduledExecutorService接口介绍
- (转)ScheduledExecutorService接口
- 定时任务接口ScheduledExecutorService
- ScheduledExecutorService执行定时任务接口
- java定时任务接口ScheduledExecutorService
- java定时任务接口ScheduledExecutorService
- java定时任务接口ScheduledExecutorService
- java定时任务接口ScheduledExecutorService
- java定时任务接口ScheduledExecutorService
- 使用ScheduledExecutorService疑惑
- ScheduledExecutorService的使用
- ScheduledExecutorService的使用
- ScheduledExecutorService的使用
- ScheduledExecutorService的使用
- 前端开发框架Bootstrap和KnockoutJS
- linux操作系统基础(4)文件系统和磁盘管理
- umask
- Apache shutdown unexpectedly解决方法
- Leetcode: Plus One
- ScheduledExecutorService接口使用
- Flex 对ArrayCollection的重构
- 黑马程序员——JAVA基础——线程---概述,创建、生命周期,控制,同步,线程通信
- MVVM架构~knockoutjs系列之从Knockout.Validation.js源码中学习它的用法
- Leetcode:Merge Two Sorted Lists
- Python编程基础之十四正则表达式
- Flex中ArrayCollection的复制(克隆)
- IOS设置UIView的边框为圆角
- Leetcode: Length of Last Word