java线程池创建与调用

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);
    }
  •  参数解析
序号名称类型含义
1corePoolSizeint核心线程池大小
2maximumPoolSizeint最大线程池大小
3keepAliveTimelong线程最大空闲时间
4unitTimeUnit时间单位
5workQueueBlockingQueue<Runnable>线程等待队列
6threadFactoryThreadFactory线程创建工厂
7handlerRejectedExecutionHandler拒绝策略

 

  • 以下代码为调用代码
     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());
    }
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值