最近在和线程打交道,要同时启动多个线程,并且每个线程要做不同的任务,最开始,我用的是Thread,写了几个main函数来start,不过我现在发现这个方法我觉得很水,所以翻了下java的API,看到了ScheduledExecutorService这个类里面有个线程池的方法,很给力的样子,于是我就试了试。
这个类里面主要就是两个方法:
1.scheduleAtFixedRate(Runnable command, long initialDelay,long period,TimeUnit unit)
创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,然后在 initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。如果任务的任一执行遇到异常,都会取消后续执行。否则,只能通过执行程序的取消或终止方法来终止该任务。
2.scheduleWithFixedDelay(Runnable command,long initialDelay, long delay,TimeUnit unit)
创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。如果任务的任一执行遇到异常,就会取消后续执行。否则,只能通过执行程序的取消或终止方法来终止该任务。
实现代码如下:
package com.cnas.thread;
import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.cnas.csvAnalysis.Analyze;
import com.cnas.dispatchPool.ListDir;
import com.cnas.ftp.FTPDownload;
import com.cnas.global.GlobalsConfig;
/**
* 线程池
* @author yKF41624
* @date 2011-8-26 modified by yang
*/
public class StartDispatch {
private static File file = new File(GlobalsConfig.getfileuploadFlode());
private ScheduledExecutorService sch = Executors.newScheduledThreadPool(1);
public StartDispatch() {
System.out.println("All Threads Started!");
}
/**
* 扫描文件目录线程
*/
public void scanFile() {
Runnable runnable = new Runnable() {
public void run() {
System.out.println("testfile");
}
};
sch.scheduleWithFixedDelay(runnable, 1, 10, TimeUnit.SECONDS);
}
/**
* 扫描数据库
*/
public void scanDB() {
Runnable runnable = new Runnable() {
public void run() {
System.out.println("testdb...");
}
};
sch.scheduleWithFixedDelay(runnable, 1, 10, TimeUnit.SECONDS);
}
public static void main(String[] args) {
StartDispatch thread = new StartDispatch();
thread.scanFile();
thread.scanDB();
}
}