ThreadPoolExecutor最重要的构造方法如下:
- public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
方法参数如下:

ThreadPoolExecutor的使用示例,通过execute()方法提交任务。
- public static void main(String[] args) {
- ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 5, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
- for (int i = 0; i < 10; i++) {
- executor.execute(new Runnable() {
- @Override
- public void run() {
- System.out.println(Thread.currentThread().getName());
- }
- });
- }
- executor.shutdown();
- }
或者通过submit()方法提交任务
- public static void main(String[] args) throws ExecutionException, InterruptedException {
- ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 5, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
- List<Future> futureList = new Vector<>();
- //在其它线程中执行100次下列方法
- for (int i = 0; i < 100; i++) {
- futureList.add(executor.submit(new Callable<String>() {
- @Override
- public String call() throws Exception {
- return Thread.currentThread().getName();
- }
- }));
- }
- for (int i = 0;i<futureList.size();i++){
- Object o = futureList.get(i).get();
- System.out.println(o.toString());
- }
- executor.shutdown();
- }
运行结果:
- ...
- pool-1-thread-4
- pool-1-thread-3
- pool-1-thread-2
下面主要讲解ThreadPoolExecutor的构造方法中workQueue和RejectedExecutionHandler参数,其它参数都很简单。
3.2 workQueue任务队列 (编辑:西安站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|