使用Threadpoolexecutor创建线程池

Person对象

package com.chenghong.model;

public class Person implements Runnable{

    public int age;
    public String name;

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println("正在执行task "+this.age);
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

创建线程池

package com.chenghong;

import com.chenghong.model.Person;

import java.util.concurrent.*;

public class Demo01 {

    public static void main(String[] args) {
        //核心线程数
        int corePoolSize =3;
        //最大线程数
        int maximumPoolSize=6;
        //超过corePoolSize线程数线程的等待时间
        long keepAliveTime =2;
        //以秒为时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        //任务等待队列
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(3);
        ThreadPoolExecutor executor = null;
        try{
            //AbortPolicy 拒绝策略 抛出RejectedExecutionException
            //CallerRunsPolicy 超过最大线程数 队列也满的情况下 会创建一个新线程去提交任务
            //DiscardOldestPolicy 占用队列最前面任务  抛弃占用的队列任务
            //DiscardPolicy 拒绝的任务直接丢弃
            executor = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue,new ThreadPoolExecutor.AbortPolicy());
            //循环提交任务
            for(int i =0;i<8;i++){
                final  int index = i+1;
                Future task =executor.submit(new Person(i,"a") {
                        @Override
                        public void run() {
                            System.out.println("我是线程:"+index+"开始执行");
                            try {
                                //模拟执行任务时间 10秒
                                Thread.sleep(30000);
                                System.out.println("线程:"+index+"--执行完毕");
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                });
                //线程休眠500ms 保证提交顺序
                Thread.sleep(500);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭线程
            if(null!=executor){
                executor.shutdown();
            }
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值