Java并发编程之线程管理(Executor框架15)
2014-03-30 23:21
573 查看
4.5指定一段时间运行并发任务
当你发送一个任务给指定的executor时,它依据executor的配置来迅速被运行。当你对线程的运行不太感兴趣,只需要它快速的运行就可以了,这就是它的使用场合。当你想间歇地执行一个任务或者定期地执行一个任务。对于这些目的,Executor框架提供了一个ScheduledThreadPoolExecutor类。请看下面实例实例代码。定义Task类,实现一个简单的逻辑。
import java.util.Date; import java.util.concurrent.Callable; import java.util.concurrent.Executors; importjava.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * This class implements the task ofthis example. Writes a * message to the console with theactual date and returns the * 'Hello, world' string * */ public class Task implements Callable<String> { /** * Name of the task */ private Stringname; /** * Constructor of the class * @param name Name of the task */ public Task(String name) { this.name=name; } /** * Main method of the task. Writes a message tothe console with * the actual date and returns the 'Helloworld' string */ @Override public String call()throws Exception { System.out.printf("%s: Starting at : %s\n",name,new Date()); return"Hello, world"; } /** * Main method of the example * @param args */ public staticvoidmain(String[] args) { // Create a ScheduledThreadPoolExecutor ScheduledExecutorService executor=(ScheduledExecutorService)Executors.newScheduledThreadPool(1); System.out.printf("Main: Starting at: %s\n",new Date()); // Send the tasks to the executor with the specified delay for (int i=0; i<5; i++) { Task task=new Task("Task "+i); executor.schedule(task,i+1 ,TimeUnit.SECONDS); } // Finish the executor executor.shutdown(); // Waits for the finalization of the executor try { executor.awaitTermination(1,TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } // Writes the finalization message System.out.printf("Core: Ends at: %s\n",new Date()); } }
运行结果:
Main:Starting at: Sun Mar 30 23:03:12 CST 2014 Task0: Starting at : Sun Mar 30 23:03:13 CST 2014 Task1: Starting at : Sun Mar 30 23:03:14 CST 2014 Task2: Starting at : Sun Mar 30 23:03:15 CST 2014 Task3: Starting at : Sun Mar 30 23:03:16 CST 2014 Task4: Starting at : Sun Mar 30 23:03:17 CST 2014 Core:Ends at: Sun Mar 30 23:03:17 CST 2014
相关文章推荐
- Java并发编程之线程管理(Executor框架16)
- Java并发编程之线程管理(Executor框架12)
- Java线程与并发编程实践----并发工具类与Executor框架
- Java线程与并发编程实践----锁框架
- java并发编程之线程管理
- Java并发编程-Executor框架之CompletionService
- java并发编程-Executor框架
- Java并发编程之线程管理(基本线程同步2)
- Executor框架简介-java并发编程
- Java并发编程之线程管理(基本线程同步4)
- JAVA 并发编程之线程管理2
- Java并发编程核心方法与框架-ExecutorService的使用
- Java并发编程核心方法与框架-ScheduledExecutorService的使用
- Java并发编程-Executor框架之Callable和Future接口
- 【Java并发编程】:并发新特性—Executor框架与线程池(含代码)
- Java并发编程:Executor框架
- 【Java并发编程】之十九:并发新特性—Executor框架与线程池(含代码)
- Java并发编程核心方法与框架-ExecutorService的使用
- Java并发编程之线程管理(高级线程同步8)
- java并发编程-Executor框架详解