天下任我行
allowmego
全部博文(46)
2013年(4)
2012年(12)
2011年(3)
2010年(5)
2009年(16)
2008年(6)
风林火山
yangyefe
wzongrui
sww_lyu
sxwxyfp
三角湖的
yanhaili
suse110
childish
分类: Java
2009-05-25 14:51:13
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(); } } }
上一篇:ThreadPoolExecutor例程
下一篇:查看jdk的版本是32位还是64位的方法
登录 注册