1. 程式人生 > >Java多執行緒 ScheduledThreadPoolExecutor 計劃任務類的使用

Java多執行緒 ScheduledThreadPoolExecutor 計劃任務類的使用

               

前面我們已經學習了使用ThreadPoolExecutor類來實現自動建立和執行執行緒。但是那些執行緒都是一提交就會執行

,我們有時候希望不要一提交就執行,而是延遲一段時間或者週期性的執行某個任務,這樣我們該怎麼辦呢,下面就介

紹這個類ScheduledThreadPoolExecutor,他就能幫助我們實現這樣的效果,程式碼如下。


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<String> {  private String name;  public Task(String name)
{  super();  this.name = name; } @Override public 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()); }}


可以看到執行結果

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

雖然都是同時提交的任務,dan'shi

           

再分享一下我老師大神的人工智慧教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智慧的隊伍中來!https://blog.csdn.net/jiangjunshow