java定时器可以使用Thread线程实现,Timer,以及
需要用Thread创建线程,这里就不代码了
- public static void main(String[] args) {
- Timer timer = new Timer();
- timer.schedule(new TimerTask() {
- @Override
- public void run() {
- System.out.println("Timer的第一个定时器:" + new Date());
- }
- }, 0, 2000);
- }
使用线程池方式创建定时任务
- public static void main(String[] args) {
- ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(2);
- executorService.scheduleAtFixedRate(() -> System.out.println("ThreadPool第一个定时器:" + new Date())
- , 0, 2, TimeUnit.SECONDS);
- }
timer本质上还是单线程实现,,而ScheduledThreadPoolExecutor是基于线程池方式创建的,所以可以实现多线程定时器,可见ScheduledThreadPoolExecutor的性能是最高的,所以平时建议用ScheduledThreadPoolExecutor创建定时器