多线程

Java中的线程池的使用--ThreadPoolExecutor

2020-12-03  本文已影响0人  冰花水焰

ThreadPoolExecutor参数介绍

1、corePoolSize:核心线程数,核心线程会一直存活,即使没有任务
2、maximumPoolSize:线程池中的最大线程数
3、workQueue:阻塞队列的容量,用来存储等待执行的任务
4、keepAliveTime:线程空闲时间
5、ThreadFactory:线程工厂
5、RejectedExecutionHandler:拒绝策略
6、TimeUnit 时间单位

提交任务的方式

提交任务种类

  1. Runnable
  2. Callable
    区别:Runnable 不会返回结果,并且无法抛出经过检查的异常

代码实现

public class ThreadPoolTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //阻塞队列
        BlockingQueue bq = new ArrayBlockingQueue(2);
        //线程工厂
        ThreadFactory factory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r);
            }
        };
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 2, 60, TimeUnit.SECONDS,bq,factory,new ThreadPoolExecutor.CallerRunsPolicy());

        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"sss");
            }
        });
        Future<?> ft = threadPoolExecutor.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("zhe gai zen me ban");
                int a = 1;

            }
        });
        try{Thread.sleep(100);}catch (Exception e){}
        System.out.println(ft.isDone());

        Future<Object> submit = threadPoolExecutor.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return "小猪佩奇";
            }
        });
        try{Thread.sleep(1000);}catch (Exception e){}
        System.out.println(submit.get());
    }
}
上一篇下一篇

猜你喜欢

热点阅读