7. 阻塞队列和线程池
BlockingQueue什么时候会用到:多线程并发处理,线程池
超时等待
同步队列
Excutors创建线程池
public class Demo01 { public static void main(String[] args) { ExecutorService executorService = Executors.newSingleThreadExecutor();//单个线程 //ExecutorService executorService = Executors.newFixedThreadPool(5);//创建一个固定线程池的大小 //ExecutorService executorService = Executors.newCachedThreadPool();//可伸缩的线程池 try { for (int i = 0; i <10 ; i++) { //线程池创建线程的方法 executorService.execute(()->{ System.out.println(Thread.currentThread().getName()+"ok"); }); } } catch (Exception e) { e.printStackTrace(); }finally { //线程池使用完需要关闭 executorService.shutdown(); } } }
public class Demo2 { public static void main(String[] args) { //自定义线程池(工作常用) //其他的拒绝策略 //ThreadPoolExecutor.CallerRunsPolicy(); 从哪来回哪去,回到main线程 //ThreadPoolExecutor.DiscardOldestPolicy(); 队列满了尝试和最早的队列竞争,不会抛出异常 //ThreadPoolExecutor.DiscardPolicy(); 队列满了不会抛出异常,丢掉任务 ExecutorService threadPool=new ThreadPoolExecutor(//第三个参数,超过3s就不等了 2, 5, 3, TimeUnit.SECONDS ,new LinkedBlockingDeque<>(3) , Executors.defaultThreadFactory() , new ThreadPoolExecutor.AbortPolicy()//如果队列满了还有进来的就不处理这个线程并且抛出异常 ); try { //当i<5时,只会有两个线程取处理业务,因为阻塞队列还没有溢出 // 如果i<6就会开启maxPoolSize 使用i-3个线程取处理业务 //如果i>8 RejectedExecutionException 最大承载=Deque+max for (int i = 0; i <8 ; i++) { //线程池创建线程的方法 threadPool.execute(()->{ System.out.println(Thread.currentThread().getName()+"ok"); }); } } catch (Exception e) { e.printStackTrace(); }finally { //线程池使用完需要关闭 threadPool.shutdown(); } } }
如何定义最大线程呢
1. CPU密集型 12核->12条线程同时执行,需要通过代码获取不能写死
Runtime.getRuntime().availableProcessors()