java 线程池 ThreadPoolExecutor 的简单示例

  • 线程的实现方式

    • java 多线程之 extends Thread

    • java 多线程之 implements Runnable

    • java 多线程之 implements Callable

  • 线程池的使用

    • 线程池简介

    • ThreadPoolExecutor

      • java 线程池之 newScheduledThreadPool

      • java 线程池之 newCachedThreadPool

      • java 线程池之 newFixedThreadPool

      • java 线程池之 newSingleThreadExecutor

    • ForkJoinPool

      • java 线程池之 newWorkStealingPool

java  线程池 ThreadPoolExecutor 的UML类图:

java 线程池 ThreadPoolExecutor 的简单示例_第1张图片

简单示例:

public class ThreadPoolTest {
    // 线程
    final static int corePoolSize = 5;
    // 最大线程数
    final static int maximumPoolSize = 10;
    // 空闲存活时间
    final static long keepAliveTime = 0;
    // 存活时间的单位
    final static TimeUnit unit = TimeUnit.SECONDS;
    // 线程数
    final static int threads = 20;
    // 计数器,用于等待子线程执行完毕
    CountDownLatch countDownLatch = new CountDownLatch(threads);
    // 线程池的阻塞队列 LinkedBlockingQueue、SynchronousQueue、ArrayBlockingQueue、LinkedTransferQueue、PriorityBlockingQueue
    LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue();

    /**
     * 线程池测试 execute
     *
     * @throws InterruptedException InterruptedException
     */
    @Test
    public void threadPoolTest1() throws InterruptedException {
        System.out.println("-------- begin ----------");
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                keepAliveTime, unit,
                linkedBlockingQueue);
        for (int i = 0; i < threads; i++) {
            final int finalI = i;
            threadPoolExecutor.execute(() -> {
                try {
                    printThreadInfo(threadPoolExecutor, finalI);
                } catch (Exception e) {
                    System.out.println(e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        System.out.println("-------- end ----------");
    }

    /**
     * 线程池测试 submit runnable
     *
     * @throws InterruptedException InterruptedException
     */
    @Test
    public void threadPoolTest2() throws InterruptedException {
        System.out.println("-------- begin ----------");
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                keepAliveTime, unit,
                linkedBlockingQueue);
        for (int i = 0; i < threads; i++) {
            final int finalI = i;
            threadPoolRunnable runnable = new threadPoolRunnable(threadPoolExecutor, finalI);
            Future submit = threadPoolExecutor.submit(new Thread(runnable));
            // 这个会等待执行结果
//            Object o = submit.get();
//            System.out.println(o);
        }
        countDownLatch.await();
        System.out.println("-------- end ----------");
    }

    /**
     * 线程池测试 submit callable
     *
     * @throws InterruptedException
     * @throws ExecutionException
     */
    @Test
    public void threadPoolTest3() throws InterruptedException, ExecutionException {
        System.out.println("-------- begin ----------");
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                keepAliveTime, unit,
                linkedBlockingQueue);
        for (int i = 0; i < threads; i++) {
            final int finalI = i;
            threadPoolCallable callable = new threadPoolCallable(threadPoolExecutor, finalI);
            FutureTask futureTask = new FutureTask<>(callable);
            Future submit = threadPoolExecutor.submit(new Thread(futureTask));
            // 这个会等待执行结果
            Object o = futureTask.get();
            System.out.println(o);
        }
//        countDownLatch.await();
        System.out.println("-------- end ----------");
    }

    /**
     * Runnable 内部类
     */
    private class threadPoolRunnable implements Runnable {
        ThreadPoolExecutor threadPoolExecutor;
        int finalI;

        /**
         * 构造函数
         *
         * @param threadPoolExecutor 线程池
         * @param finalI             i
         */
        public threadPoolRunnable(ThreadPoolExecutor threadPoolExecutor, int finalI) {
            this.threadPoolExecutor = threadPoolExecutor;
            this.finalI = finalI;
        }

        /**
         * run
         */
        @Override
        public void run() {
            try {
                printThreadInfo(threadPoolExecutor, finalI);
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                countDownLatch.countDown();
            }
        }
    }

    /**
     * Callable 内部类
     */
    private class threadPoolCallable implements Callable {
        ThreadPoolExecutor threadPoolExecutor;
        int finalI;

        /**
         * 构造函数
         *
         * @param threadPoolExecutor 线程池
         * @param finalI             i
         */
        public threadPoolCallable(ThreadPoolExecutor threadPoolExecutor, int finalI) {
            this.threadPoolExecutor = threadPoolExecutor;
            this.finalI = finalI;
        }

        /**
         * Computes a result, or throws an exception if unable to do so.
         *
         * @return computed result
         * @throws Exception if unable to compute a result
         */
        @Override
        public String call() {
            try {
                printThreadInfo(threadPoolExecutor, finalI);
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                countDownLatch.countDown();
            }
            return Thread.currentThread().getName();
        }
    }

    /**
     * 打印线程池相关信息
     *
     * @param threadPoolExecutor 执行器
     * @param finalI             i
     */
    private void printThreadInfo(ThreadPoolExecutor threadPoolExecutor, int finalI) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("\r\n");
        stringBuffer.append("threadName=" + Thread.currentThread().getName());
        stringBuffer.append("\r\n");
        stringBuffer.append("finalI=" + finalI);
        stringBuffer.append("\r\n");
        stringBuffer.append("countDownLatch=" + countDownLatch.getCount());
        stringBuffer.append("\r\n");
        stringBuffer.append("getCorePoolSize=" + threadPoolExecutor.getCorePoolSize());
        stringBuffer.append("\r\n");
        stringBuffer.append("getPoolSize=" + threadPoolExecutor.getPoolSize());
        stringBuffer.append("\r\n");
        stringBuffer.append("getQueue=" + threadPoolExecutor.getQueue().size());
        stringBuffer.append("\r\n");
        stringBuffer.append("getLargestPoolSize=" + threadPoolExecutor.getLargestPoolSize());
        stringBuffer.append("\r\n");
        stringBuffer.append("getMaximumPoolSize=" + threadPoolExecutor.getMaximumPoolSize());
        stringBuffer.append("\r\n");
        stringBuffer.append("getTaskCount=" + threadPoolExecutor.getTaskCount());
        stringBuffer.append("\r\n");
        stringBuffer.append("getThreadFactory=" + threadPoolExecutor.getThreadFactory().getClass().getSimpleName());
        stringBuffer.append("\r\n");
        stringBuffer.append("getRejectedExecutionHandler=" + threadPoolExecutor.getRejectedExecutionHandler().getClass().getSimpleName());
        stringBuffer.append("\r\n");
        System.out.println(stringBuffer.toString());
    }
}

你可能感兴趣的:(Java)