java 简单线程池创建

开发中,经常会碰到有时间为了性能而编写线程做异步请求,

这是公用线程池,如果需要用完就删除,建议不要使用线程池,直接手动 new thread 创建线程去操作

// 线程池管理类(饿汉模式加载)

public ThreadPoolExecutor(
  int corePoolSize, // 核心线程数,即最小线程数
  int maximumPoolSize, // 最大线程数,只有当workQueue队列填满时才会创建多于corePoolSize的线程
  long keepAliveTime, TimeUnit unit, // 非核心线程的空闲时间超过keepAliveTime就会被自动终止回收,corePoolSize=maxPoolSize时,keepAliveTime参数也就不起作用了(因为不存在非核心线程)
  BlockingQueue<Runnable> workQueue, // 任务的排队队列
  ThreadFactory threadFactory, // 新线程的产生方式
  RejectedExecutionHandler handler) // 拒绝策略,取值有AbortPolicy、CallerRunsPolicy、DiscardOldestPolicy、DiscardPolicy
)
public class CreateThreadPoolUtil {
    // 最原始的方式创建线程池
    private static final ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
            8, 32, 60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(128), Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());
 
    public static ThreadPoolExecutor getInstance() {
        return poolExecutor;
    }
}
 
 
 
 

public class TestTransactionalServiceImpl implements TestTransactionalService {
 
    public void testTransactional() throws ExecutionException, InterruptedException {
        int inter = 3;
        ThreadPoolExecutor poolExecutor = CreateThreadPoolUtil.getInstance();
        FutureTask[] integerFuture = new FutureTask[inter];
        for (int i = 0; i < inter; i++) {
            int finalI = i + 1;
            integerFuture[i] = new FutureTask<>(() -> {
                return new TransactionCallback<String>() {
                    @Override
                    public String doInTransaction(TransactionStatus transactionStatus) {
                        System.out.println("多线程运行了---" + finalI);
                        return "业务执行成功";
                    }
                };
            });
            poolExecutor.execute(integerFuture[i]);
        }
        for (int i = 0; i < inter; i++) {
                System.out.println("integerFuture返回结果 = " + i + "==" + integerFuture[i].get());
        }
 
        ThreadMXBean bean = ManagementFactory.getThreadMXBean();
        System.out.println("线程总数为 = " + bean.getThreadCount());
 
    }
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值