This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

A project thread pool application

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(" no object found,notifyId:{}",notifyId); return true; }}}; Future future = pool.submit(callable); stopWatch.stop(); Log.info ("notifyId:{} notifies execution results; Available: {} {} ms, "notifyId, future. The get (), a stopWatch. GetTotalTimeMillis ());Copy the code

Two thread pool code analysis

ExecutorService pool = new ThreadPoolExecutor(3, 6,
        0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
Copy the code
  1. Thread pool parameters

    The initial thread count is 3, the maximum thread count is 6, the thread lifetime is 0 ms, the LinkedBlockingQueue is used, the production consumption block queue is used, the internal ReentrantLock and Condition are used to synchronize the production and consumption, its length is 1024. The next two parameters specify the name of the thread pool to facilitate troubleshooting.

  2. Thread pool execution

    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(" no object found,notifyId:{}",notifyId); return true; }}}; Future future = pool.submit(callable); stopWatch.stop();Copy the code

    Use pool.submit(callable); There is another method called excute() for executing the thread. What’s the difference between the two? The Pool.submit class calls the Callable class and returns the Future. The return value is then used to determine whether the thread in the thread pool executed successfully. The excute() method does not return a value. It does not care about the return value information of the method.

  3. A StopWatch class

    It has nothing to do with Line City, it is actually a timer class

     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());
    Copy the code

    With this we can better output the running time of the method.