日期:2014-05-20 浏览次数:20668 次
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class PDFTool2 {
private final static Integer ThreadNum = 3;
private final static ExecutorService exec = Executors.newCachedThreadPool();//创建线程池
public static void main(String[] args) throws Exception {
//存放结果的队列
ConcurrentLinkedQueue<Future<Integer>> queue = new ConcurrentLinkedQueue<Future<Integer>>();
runDaemon(queue);
for(int i=0; i<ThreadNum; i++){
Future<Integer> future = exec.submit(getTask());
queue.add(future);
}
}
//运行后台线程,用于控制线程个数
public static void runDaemon(final ConcurrentLinkedQueue<Future<Integer>> queue){
Thread thread = new Thread(new Runnable(){
public void run() {
while(true){
try {
TimeUnit.SECONDS.sleep(5);//10秒监听一次
} catch (InterruptedException e) {e.printStackTrace();}
int UserThreadNum = getUserThreadNum();//用户输入的线程个数
int CurrentThreadNum = queue.size();//当前的线程个数
System.out.println("监听线程启动:当前有"+CurrentThreadNum+"个线程."+(UserThreadNum>0?"用户输入了"+UserThreadNum+"个线程.":""));
if(UserThreadNum > CurrentThreadNum){//添加几个线程
for(int i=0; i<(UserThreadNum-CurrentThreadNum); i++){
Future<Integer> future = exec.submit(getTask());
queue.add(future);
System.out.println("添加了一个任务-------------------------");
}
}else if(UserThreadNum < CurrentThreadNum){//关闭几个线程
for(int i=0; i<(CurrentThreadNum-UserThreadNum); i++){
Future<Integer> future = queue.poll();
if(future != null){
boolean isSucc = future.cancel(true);//该任务被取消
System.out.println("取消了一个任务-------------------------"+isSucc);
}
}
}
//如果任务中有完成的,则把它踢出队列中
Iterator<Future<Integer>> iter = queue.iterator();
boolean isComp = false;
while(iter.hasNext()){
Future<Integer> future = iter.next();
if(future!=null && future.isDone()){
boolean isRemove = queue.remove(future);
System.out.println("一个任务已经完成,被移除.........."+isRemove);
isComp = true;
}
}
if(!isComp){System.out.println("没有一个任务已完成............");}
}
}}
);
thread.setDaemon(true);//设为后台线程
thread.start();
}
//获得用户输入的线程个数
public synchronized static int getUserThreadNum(){
return 2;
}
//获得任务
public static Callable<Integer> getTask(){
Callable<Integer> task = new Callable<Integer>(){
public Integer call() throws Exception {
process();
return 0;
}
};
return task;
}
//处理过程
public static void process(){
try {
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"完成.");