1 创建线程池
通过static代码块创建线程池:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit;
@SuppressWarnings("all") public class HttpApiThreadPool {
private static int cpuNums = Runtime.getRuntime().availableProcessors();
private static int corePoolSize = 10;
private static int maximumPoolSize = cpuNums * 5;
public static ExecutorService httpApiThreadPool = null;
static { httpApiThreadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(100), new ThreadFactoryBuilder().setNameFormat("PROS-%d").build()); }
public static boolean haveIdleThread(){ if(getActiveCount()<maximumPoolSize){ return true; } return false; }
public static int getActiveCount() { System.out.println(((ThreadPoolExecutor) httpApiThreadPool).getActiveCount()); return ((ThreadPoolExecutor) httpApiThreadPool).getActiveCount(); }
}
|
注意:
1.阿里巴巴Java开发手册中明确指出:”线程池不允许使用Excutors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让程序员更加明确线程池的运行规则,避免资源耗尽的风险”。
2.new ThreadFactoryBuilder().setNameFormat("PROS-%d").build()
给每个线程命名,方便调试。
2 使用线程池
配合Java 8的lambdas表达式去使用:
1 2 3 4 5
| HttpApiThreadPool.httpApiThreadPool.execute( ()->{ } );
|