当前位置 : 主页 > 编程语言 > c++ >

Java----多线程----ThreadPoolExecutor的正确使用

来源:互联网 收集:自由互联 发布时间:2021-06-30
ExecutorService的使用 public class ThreadPoolDemo { public static void main(String[] args) { /* * 使用Executors框架生成ThreadPool */ ExecutorService executorService = Executors.newFixedThreadPool(4); for (int i = 0; i 10; i++) { in
ExecutorService的使用
public class ThreadPoolDemo {

    public static void main(String[] args) {

        /*
         * 使用Executors框架生成ThreadPool
         */
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        
        for (int i = 0; i < 10; i++) {
            int index = i;
            executorService.submit(() -> System.out.println("i:" + index + " executorServiceByExecutors"));
        }
        executorService.shutdown();
    }
}
ThreadPoolExecutor的使用
public class ThreadPoolDemo {

    public static void main(String[] args) {

        /*
         * 自定义的ThreadPoolExecutor,但是使用的是默认的形式
         * int corePoolSize,
         * int maximumPoolSize,
         * long keepAliveTime,
         * TimeUnit unit,
         * BlockingQueue
 
   workQueue,
         * ThreadFactory threadFactory,
         * RejectedExecutionHandler handler
         */
        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i < 10; i++) {
            int index = i;
            pool.submit(() -> System.out.println("i:" + index + " executorService"));
        }
        pool.shutdown();
    }
}
 
ExecutorService和ThreadPoolExecutor的使用
public class ThreadPoolDemo {

    public static void main(String[] args) {

        ExecutorService executorService = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i < 10; i++) {
            int index = i;
            executorService.submit(() -> System.out.println("i:" + index + "executorService"));
        }
        executorService.shutdown();
    }
}
自定义ThreadFactory、拒绝策略以及重写ThreadPoolExecutor的beforeExecute、afterExecute、terminated方法
public class ThreadPoolDemo2 {

    public static void main(String[] args) {
       
        ExecutorService executorService = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), r -> {
            Thread thread = new Thread(r);
            thread.setName(r.getClass().getName());
            return thread;
        }, new ThreadPoolExecutor.AbortPolicy()) {
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                super.beforeExecute(t, r);
                System.out.println("beforeExecute");
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                System.out.println("afterExecute");
            }

            @Override
            protected void terminated() {
                super.terminated();
                System.out.println("terminated");
            }
        };

        for (int i = 0; i < 10; i++) {
            int index = i;
            /*
             *如果直接使用 submit进行提交的话,如果县城中运行的有错误的话,就不会显示出来堆栈信息
             */
            executorService.submit(() -> System.out.println("i:" + index));
        }

        executorService.shutdown();
    }
}
submit和future的区别
/**
 * 错误信息如果使用submit则无法显示,一种方式是放弃使用submit,另一种是可以使用execute
 */
public class ThreadPoolDemo3 {

    public static void main(String[] args) {

        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10), Executors.defaultThreadFactory());

        for (int i = 0; i < 5; i++) {
            int index = i;
            pool.submit(() -> divTask(100, index));

            Future future = pool.submit(() -> divTask(100, index));
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        pool.shutdown();
    }

    private static void divTask(int a, int b) {
        double result = a / b;
        System.out.println(result);
    }
}
如何打印错误的堆栈信息
/**
 * 直接使用ExecutorService pool = Executors.newFixedThreadPool(2);  pool.submit()也不会出现错误的堆栈信息
 * 错误信息如果使用submit则无法显示,一种方式是放弃使用submit,另一种是可以使用execute
 */
public class ThreadPoolDemo4 {

    public static void main(String[] args) {

        ExecutorService pool = Executors.newFixedThreadPool(2);

        for (int i = 0; i < 5; i++) {
            int index = i;
            /*
             * 不会出现错误的堆栈信息
             */
            pool.submit(() -> divTask(100, index));

            //1、可以使用Future future = pool.submit();实现错误信息堆栈信息
            Future future = pool.submit(() -> divTask(100, index));
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

            //2、可以使用pool.execute();实现错误信息堆栈信息
            pool.execute(() -> divTask(100, index));
        }
        pool.shutdown();
    }

    private static void divTask(int a, int b) {
        double result = a / b;
        System.out.println(result);
    }
}
自定义继承ThreadPoolExecutor
public class TraceThreadPoolExecutor extends ThreadPoolExecutor {

    public TraceThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue
 
   workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    public Future
   submit(Runnable task) {
        return super.submit(wrap(task, clientTrace(), Thread.currentThread().getName()));
    }

    private Runnable wrap(Runnable task, Exception clientTrace, String currentThreadName) {
        return () -> {
            try {
                task.run();
            } catch (Exception e) {
                clientTrace.printStackTrace();
                throw e;
            }
        };
    }

    private Exception clientTrace() {
        return new Exception("Client stack trace");
    }

    public static void main(String[] args) {
        ThreadPoolExecutor pool = new TraceThreadPoolExecutor(0, Integer.MAX_VALUE, 0L, TimeUnit.SECONDS, new SynchronousQueue<>());

        for (int i = 0; i < 5; i++) {
            int index = i;
            pool.execute(() -> divTask(100, index));
        }
    }

    private static void divTask(int a, int b) {
        double result = a / b;
        System.out.println(result);
    }
}
 
网友评论