分类: Java
2011-01-03 20:11:09
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TestThreadPool {
private static int consumeTaskSleepTime = 2000;
private static int produceTaskMaxNumber = 10;
public static void main(String[] args) {
// 构造一个线程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 3,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10),
new ThreadPoolExecutor.DiscardOldestPolicy());
ArrayList<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>();
for (int i = 1; i <= produceTaskMaxNumber; i++) {
try {
// 产生一个任务,并将其加入到线程池
String task = "task@ " + i;
System.out.println("put " + task);
FutureTask<String> futureTask = new FutureTask<String>(new ThreadPoolTask(task));
threadPool.execute(futureTask);
tasks.add(futureTask);
} catch (Exception e) {
e.printStackTrace();
}
}
for(FutureTask<String> futureTask : tasks) {
try {
// 1秒内获得结果
String str = "stop " + futureTask.get(1, TimeUnit.SECONDS);
System.out.println(str);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 线程池执行的任务
*
* @author hdpan
*/
public static class ThreadPoolTask implements Callable<String> {
private static final long serialVersionUID = 0;
// 保存任务所需要的数据
private String threadPoolTaskData;
ThreadPoolTask(String tasks) {
this.threadPoolTaskData = tasks;
}
public String call() throws Exception {
// TODO Auto-generated method stub
System.out.println("start .." + threadPoolTaskData);
try {
Thread.sleep(consumeTaskSleepTime);
} catch (Exception e) {
e.printStackTrace();
}
return threadPoolTaskData.toUpperCase();
}
}
}
chinaunix网友2011-01-05 11:10:51
很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com