public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); }
package threadpool; import java.util.List; import java.util.concurrent.*; public class ThreadPoolTest { public static void main(String[] args) { //创建固定大小的线程池 ExecutorService executorService = Executors.newFixedThreadPool(2); //创建只有1个线程的线程池 ExecutorService executorService1 = Executors.newSingleThreadExecutor(); //创建一个不限线程上限的线程池,任何提交的任务度可以立刻执行 ExecutorService executorService2 = Executors.newCachedThreadPool(); //线程池的工作顺序 //corepoolsize-》任务队列--》maximumPoolSize->拒绝策略 //向线程池提交的2种类型的任务 Runnable,Callable //1、方法签名不一样 void Runnable.run() V Callable.call() throws Exception //2 是否允许有返回值 Callable允许 //3 是否允许抛一场 Callable允许 //三种提交任务方式 Future<?> submit = executorService.submit(new Runnable() { @Override public void run() { } }); Future<String> submit1 = executorService.submit(new Callable<String>() { @Override public String call() throws Exception { return "null"; } }); //正确使用线程池 //避免使用无边界队列 ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(512), new ThreadPoolExecutor.AbortPolicy()); //线程池的拒绝策略 //ThreadPoolExecutor.AbortPolicy :抛出异常; ThreadPoolExecutor.DiscardPolicy 什么也不做 //ThreadPoolExecutor.DiscardOldestPolicy 丢弃执行队列最老的任务,尝试为当前提交的任务腾出空间 // ThreadPoolExecutor.CallerRunsPolicy 直接有提交任务这执行这个任务 // 获取结果以及异常 try { String s = submit1.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } //正确使用线程池子 } void testLaunch(ExecutorService executorService, List<Runnable> runnableList){ CountDownLatch countDownLatch=new CountDownLatch(runnableList.size()); for (Runnable r:runnableList){ executorService.submit(new Runnable() { @Override public void run() { try { r.run(); }finally { countDownLatch.countDown(); } } }); } countDownLatch.await(10,TimeUnit.SECONDS); } }
文章评论