Chinaunix首页 | 论坛 | 博客
  • 博客访问: 179685
  • 博文数量: 46
  • 博客积分: 1445
  • 博客等级: 上尉
  • 技术积分: 448
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-27 22:20
文章分类

全部博文(46)

文章存档

2013年(4)

2012年(12)

2011年(3)

2010年(5)

2009年(16)

2008年(6)

我的朋友

分类: 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();
        }
    }
}

阅读(3296) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~