美文网首页
实战! 多线程线程池分析

实战! 多线程线程池分析

作者: 进击的三文鱼 | 来源:发表于2021-05-15 23:43 被阅读0次

    一 项目线程池运用

    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());
    
    1. 线程池参数

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

    2. 线程池的执行

       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()方法是没有返回值的,他不去关注方法的返回值信息。

    3. 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());
      

      通过他我们可以更好的输出方法的运行时长。

    相关文章

      网友评论

          本文标题:实战! 多线程线程池分析

          本文链接:https://www.haomeiwen.com/subject/nshljltx.html