这是介绍使用JDK 并行包之executor 第二部分,这部分介绍是如何创建一个可以调度的线程池。具体参考代码中的注释。
/*
* delay 4 seconds and run thread every 2 seconds.
*/
//ses.scheduleAtFixedRate(GetRunnable(), 4, 2, TimeUnit.SECONDS);
/*
* delay 4 seconds and run thread delay 1 second.
*/
ses.scheduleWithFixedDelay(GetRunnable(), 2, 1, TimeUnit.SECONDS);
/*
上述代码是关键。
package net.vincent.study.executor;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* This is example of using ScheduleExecutorService.
* @author wma
*/
public class Part2 {
/**
* Create scheduleThreadPool
* @param numberOfTHread in threadPool.
* @return ScheduleThreadPool
*/
public static ScheduledExecutorService getScheduleThreadPool(int numberOfThread){
if(numberOfThread <=0)
return null;
ScheduledExecutorService scheduleThreadPool = Executors.newScheduledThreadPool(numberOfThread) ;
return scheduleThreadPool;
}
/**
*
* Create Runnable
*/
public static Runnable GetRunnable(){
final Runnable runnable = new Runnable() {
int count = 0;
public void run() {
System.out.println(new Date() + " run " + (++count));
}
};
return runnable;
}
public static void main(String[] args) {
ScheduledExecutorService ses = getScheduleThreadPool(4);
System.out.println(new Date());
/*
* delay 4 seconds and run thread every 2 seconds.
*/
//ses.scheduleAtFixedRate(GetRunnable(), 4, 2, TimeUnit.SECONDS);
/*
* delay 4 seconds and run thread delay 1 second.
*/
ses.scheduleWithFixedDelay(GetRunnable(), 2, 1, TimeUnit.SECONDS);
/*
* ses should be shutdown.
*/
//ses.shutdown();
}
}