Java Multithreading ~~~ Use of ScheduledThreadPoolExecutor to schedule tasks

Source: Internet
Author: User

Java Multithreading ~~~ Use of ScheduledThreadPoolExecutor to schedule tasks

We have learned how to use the ThreadPoolExecutor class to automatically create and run threads. But those threads run as soon as they are submitted.

We sometimes want to run a task without submitting it, but delay for a period of time or periodically. What should we do?

ScheduledThreadPoolExecutor can help us achieve this effect. The Code is as follows.


package com.bird.concursey.charpet7;import java.util.Date;import java.util.concurrent.Callable;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledThreadPoolExecutor;import java.util.concurrent.TimeUnit;public class Task implements Callable
 
   {private String name;public Task(String name) {super();this.name = name;}@Overridepublic String call() throws Exception {System.out.printf("%s: Starting at : %s\n",name,new Date());return "hello world";}public static void main(String[] args) {ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);System.out.printf("Main: Starting at: %s\n",new Date());for(int i = 0; i < 5; i++) {Task task = new Task("Task " + i);executor.schedule(task, i, TimeUnit.SECONDS);}executor.shutdown();try {executor.awaitTermination(1, TimeUnit.DAYS);} catch (InterruptedException e) {e.printStackTrace();}System.out.printf("Main: Ends at: %s\n",new Date());}}
 


The running result is displayed.

Main: Starting at: Fri Sep 26 21:59:50 CST 2014Task 0: Starting at : Fri Sep 26 21:59:50 CST 2014Task 1: Starting at : Fri Sep 26 21:59:51 CST 2014Task 2: Starting at : Fri Sep 26 21:59:52 CST 2014Task 3: Starting at : Fri Sep 26 21:59:53 CST 2014Task 4: Starting at : Fri Sep 26 21:59:54 CST 2014Main: Ends at: Fri Sep 26 21:59:54 CST 2014

Although all tasks are submitted at the same time, dan 'shi

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.