随笔 高并发线程池的问题

自定义线程池中等待队列的:

线程池对应的函数:
提交任务的方式:1)execute() 2)submit()

关闭线程池 1)shutdown() 2)shutdownNow()

线程池的监控

public class ThreadPoolTest {
    public static void main(String[] args) {
        ExecutorService executor = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1)) {
            @Override protected void beforeExecute(Thread t, Runnable r) {
                System.out.println("beforeExecute is called");
            }
            @Override protected void afterExecute(Runnable r, Throwable t) {
                System.out.println("afterExecute is called");
            }
            @Override protected void terminated() {
                System.out.println("terminated is called");
            }
        };

        executor.submit(() -> System.out.println("this is a task"));
        executor.shutdown();
    }
}
beforeExecute is called
this is a task
afterExecute is called
terminated is called

有task的例子:

但是这个例子存在问题:
除数为0 没有抛出异常。
submit()方法,这个方法是一个非阻塞方法,有一个返回对象,返回的是Future对象。
改成这样就可以了。

posted @ 2021-04-19 13:52  千面鬼手大人  阅读(63)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css