public final class MyThreadPool {
/**
* 线程池大小设置,系统设计等待时间最长为3000ms,单次查询数据库大约消耗600ms
* <P>
* 故而FACTOR设置为6 FACTOR = (1+WT/ST);
*/
private static final int FACTOR = 6;
/**
* 线程池大小设置,N为CPU核心数
* <P>
* N = N * FACTOR
*/
private static final ExecutorService executorService = Executors
.newFixedThreadPool(Runtime.getRuntime().availableProcessors()
* FACTOR);
private MyThreadPool() {
}
/**
* 执行线程
*
* @param command
*/
public static void execute(Runnable command) {
executorService.execute(command);
}
@SuppressWarnings("rawtypes")
public static Future submit(Runnable task) {
return executorService.submit(task);
}
}
在定义一个类继承Thread,实现run方法,在该方法中写相关逻辑;
new一个该自定义的类,名称自定义,放在submit中,如下。
Future future = MyThreadPool.submit(qdt);
然后
/**
* 等待各个线程任务完成
* @param futures
*/
private void waitForThreads(List<Future> futures) {
if (futures != null) {
for (Future future : futures) {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
}
即可。