public class ExcutorUtil {
static ExecutorService fixedThreadPool = null;
//线程池大小,可自己定义
static final Integer nThreads = 100;
static {
if (fixedThreadPool == null) {
fixedThreadPool = new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
}
public static void execute(Thread thread) {
fixedThreadPool.execute(thread);
}
public static Future<?> submit(Callable<?> c) {
return (Future<?>) fixedThreadPool.submit(c);
}
public static void execute(Runnable runnable) {
fixedThreadPool.execute(runnable);
}
}
- 创建源码为:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }
- 参数解析
序号 名称 类型 含义 1 corePoolSize int 核心线程池大小 2 maximumPoolSize int 最大线程池大小 3 keepAliveTime long 线程最大空闲时间 4 unit TimeUnit 时间单位 5 workQueue BlockingQueue<Runnable> 线程等待队列 6 threadFactory ThreadFactory 线程创建工厂 7 handler RejectedExecutionHandler 拒绝策略
- 以下代码为调用代码
ExcutorUtil.execute(()->{ //do something });
2.countdownLatch+线城市 实现多个查询结果返回
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ThreadPoolExecutor; /** * 功能描述: <br> * 〈线程池〉 * @param: * @return: */ @Configuration public class TaskPoolExecutor { /** * 系统内部使用线程池 * @return */ @Bean public ThreadPoolTaskExecutor threadPoolTaskExecutorForRpc() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 设置核心线程数 executor.setCorePoolSize(30); // 设置最大线程数 executor.setMaxPoolSize(200); // 设置队列容量 executor.setQueueCapacity(300); // 设置线程活跃时间(秒) executor.setKeepAliveSeconds(60); // 设置默认线程名称 executor.setThreadNamePrefix("task-"); //设置拒绝策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return executor; } }
调用测试
import com.google.common.collect.Lists; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * @date: 2020-06-15 15:13 * @version: V1.0 */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) @WebAppConfiguration public class ThreadPoolTest { private static Logger logger = LoggerFactory.getLogger(ThreadPoolTest.class); @Autowired private TaskPoolExecutor taskPoolExecutor; @Test public void query(){ System.out.println(System.currentTimeMillis()); List<Object> result = Lists.newArrayList(); CountDownLatch countDownLatch = new CountDownLatch(10); for (int i = 0; i < 10; i++) { List<Object> finalResult = result; taskPoolExecutor.threadPoolTaskExecutorForRpc().execute(() -> { try { TimeUnit.MILLISECONDS.sleep(10000); finalResult.add(new Object()); } catch (InterruptedException e) { e.printStackTrace(); } finally { countDownLatch.countDown(); } }); } try { // 默认3.5s超时 boolean await = countDownLatch.await(3500, TimeUnit.MILLISECONDS); logger.info("返回值await={}",await); } catch (InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } System.out.println(System.currentTimeMillis()); } }