【Java架构师】实战 多线程线程池分析

234 篇文章 6 订阅
77 篇文章 1 订阅

一 项目线程池运用
ExecutorService pool = new ThreadPoolExecutor(3, 6,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

StopWatch stopWatch=new StopWatch();
stopWatch.start();
final String notifyId=event.notifyId;
LOG.info(“transaction.onNotifyBegin.notifyId:{}”,notifyId);
Callable callable=new Callable() {
@Override
public Boolean call() {
Transaction transaction = tradeService.findByNotifyId(notifyId);
if(transaction==null){
LOG.error(“找不到对象,notifyId:{}”,notifyId);
return true;
}
}
};

Future future = pool.submit(callable);
stopWatch.stop();
LOG.info(“notifyId:{}通知执行结果;{},用时:{}ms”,notifyId,future.get(),stopWatch.getTotalTimeMillis());
二 线程池代码分析
ExecutorService pool = new ThreadPoolExecutor(3, 6,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
线程池参数

这里面的参数分别为初始线程数3,最大线程数6,线程存活时间0毫秒,使用了LinkedBlockingQueue,生产消费的阻塞队列,内部是使用ReentrantLock和Condition来保证生产和消费的同步,他的长度是1024,而后面的两个参数就是指定线程池的名称,以方便问题的排查。

线程池的执行

StopWatch stopWatch = new StopWatch();
stopWatch.start();
final String notifyId=event.notifyId;
LOG.info(“transaction.onNotifyBegin.notifyId:{}”,notifyId);
Callable callable=new Callable() {
@Override
public Boolean call() {
Transaction transaction = tradeService.findByNotifyId(notifyId);
if(transaction==null){
LOG.error(“找不到对象,notifyId:{}”,notifyId);
return true;
}
}
};
Future future = pool.submit(callable);
stopWatch.stop();
这里面使用了pool.submit(callable); 来执行线程,还有另外一个无参的执行方法excute(),那他们之间有什么区别呢,pool.submit传入Callable类最终返回Future,而Future对象就可以获得线程执行完的返回值,然后对返回值进行判断线程池中的线程是否执行成功,而excute()方法是没有返回值的,他不去关注方法的返回值信息。扩列下我尉(同英):CGMX9880 获取更多 程序员架构学习资料,
技术也是在不断更新,我相信你也想学到最新技术,
所以你们就不要说我骗人的,加的都获取资料,
学习更上一层楼了!Java,人工智能,架构师,初级程序员提升都有!

StopWatch类

他与线城池无关,他其实是一个计时器类

StopWatch stop = new StopWatch(“TASK”);
stop.start(“TASK”);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
stop.stop();
System.out.println(stop.getTotalTimeMillis());
System.out.println(stop.prettyPrint());
通过他我们可以更好的输出方法的运行时长。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值