码迷,mamicode.com
首页 > 编程语言 > 详细

线程池创建

时间:2020-06-14 00:53:45      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:ati   lex   abort   并发   factor   bsp   blocking   policy   generate   

package net.icarefx.booking.util.threadpool;

 

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* Create by wfs on 2020/06/01
* 线程工具类
*/
public class ThreadPoolUtils {
//使用volatile关键字保其可见性
volatile private static ThreadPoolExecutor threadPool = null;

/**
* 无返回值直接执行
*
* @param runnable
*/
public static void execute(Runnable runnable) {
getThreadPool().execute(runnable);
}

/**
* 返回值直接执行
*
* @param callable
*/
public static <T> Future<T> submit(Callable<T> callable) {
return getThreadPool().submit(callable);
}

private static ThreadPoolExecutor getThreadPool() {//单例加锁创建线程池
try {
if (threadPool != null) {
return threadPool;
} else {
synchronized (ThreadPoolUtils.class) {
if (threadPool == null) {
Thread.sleep(300);
int cpuNum = Runtime.getRuntime().availableProcessors();// 获取处理器数量
System.out.println(cpuNum);
int threadNum = cpuNum * 2 + 1;// 根据cpu数量,计算出合理的线程并发数
threadPool = new ThreadPoolExecutor(
threadNum - 1,// 核心线程数
threadNum, // 最大线程数
5000, // 空闲线程存活时间
TimeUnit.MILLISECONDS,// 单位毫秒
new ArrayBlockingQueue<Runnable>(10),// 采用有界队列防止oom
Executors.defaultThreadFactory(),// 创建工厂
new ThreadPoolExecutor.AbortPolicy() {// 队列满了,当前线程数大于最大线程数的拒绝策略(抛异常)
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
super.rejectedExecution(r, e);
}
}
);
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return threadPool;
}






public static void main(String[] args){

//ExecutorService threadPool=Executors.newFixedThreadPool(5);


for (int i = 0; i < 10; i++)
{
ThreadPoolUtils.execute(new Runnable(){

@Override
public void run()
{//这里写逻辑
System.out.println(Thread.currentThread().getName()+"在运行");
// TODO Auto-generated method stub
}
});
}
}
}

线程池创建

标签:ati   lex   abort   并发   factor   bsp   blocking   policy   generate   

原文地址:https://www.cnblogs.com/6kuaifuji/p/13122368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!